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:
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:
// 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:
$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:
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:
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:
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.