Database

Yabasi provides a robust and flexible database layer, supporting various database systems and offering an intuitive API for database operations.

Configuration

Database configuration is typically stored in the config/config.php file:

config/config.php
return [
'database' => [
'driver'   => 'mysql',
'host'     => 'localhost',
'database' => 'yabasi_db',
'username' => 'root',
'password' => '',
],
];

Query Builder

Yabasi's query builder provides a convenient, fluent interface for creating and running database queries. You can use it either through models or directly with the DB facade:

QueryExamples.php
// Using Query Builder with Model
$users = User::query()
    ->where('active', true)
    ->where('age', '>', 18)
    ->orderBy('name', 'asc')
    ->limit(10)
    ->get();

// Using Query Builder with DB facade
$posts = DB::table('posts')
    ->where('status', '=', 'published')
    ->orderBy('created_at', 'desc')
    ->limit(10)
    ->get();

// Aggregates
$count = DB::table('posts')->where('status', '=', 'published')->count();

Raw Queries

For more complex queries, you can use raw SQL with parameter binding:

UserController.php
$results = DB::select('SELECT * FROM users WHERE active = ?', [true]);

$id = DB::insert('INSERT INTO users (name, email) VALUES (?, ?)', ['John', 'john@example.com']);

$affected = DB::update('UPDATE users SET status = ? WHERE id = ?', ['active', 1]);

Transactions

Yabasi supports database transactions to ensure data integrity:

TransferController.php
DB::beginTransaction();

try {
    DB::update('UPDATE accounts SET balance = balance - ? WHERE id = ?', [100, 1]);
    DB::update('UPDATE accounts SET balance = balance + ? WHERE id = ?', [100, 2]);
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    throw $e;
}

Transaction Alternative Syntax

You can also use the transaction method with a closure:

OrderController.php
DB::transaction(function() {
    DB::table('orders')->insert([
        'user_id' => 1,
        'total' => 100
    ]);
    
    DB::table('inventory')
        ->where('product_id', 1)
        ->decrement('stock', 1);
});

Migrations

Yabasi provides a powerful migration system for managing database schema:

2024_10_20_create_users_table.php
use Yabasi\Database\Schema\Blueprint;
use Yabasi\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});
}
}

These features provide a solid foundation for working with databases in your Yabasi applications. The query builder and ORM work together to offer a powerful yet intuitive interface for database operations, while migrations ensure that your database schema can be easily version-controlled and shared across different environments.

Find the documentation helpful?

Show your support by starring our project on GitHub

Star on GitHub