Migrations and seeders
A migration changes the database structure. A seeder inserts data into that structure. This example creates the tables used by Product and Category, then inserts a category and two products.
Define the migration
Generate a migration with php atom make:migration create_catalogue_tables. In the generated file under app/Database/Migrations, define the schema change in up() and its reversal in down().
<?php
use Atom\Database\Migration\Migration;
use Atom\Database\Schema\Schema;
use Atom\Database\Schema\Table;
return new class extends Migration
{
public function up(Schema $schema): void
{
$schema->create("categories", static function (Table $table): void {
$table->id();
$table->string("name");
});
$schema->create("products", static function (Table $table): void {
$table->id();
$table->string("name");
$table->integer("price");
$table->boolean("active")->default(true);
$table->integer("category_id")->nullable();
});
}
public function down(Schema $schema): void
{
$schema->drop("products");
$schema->drop("categories");
}
};
The migration creates categories first and drops them last. The nullable category_id column lets a product have no category, as in the relation examples.
Seed a few records
Generate a seeder with php atom make:seeder seed_catalogue. In the generated file under app/Database/Seeders, use the connection Atom passes to run(). Insert the category first so its generated ID can be used for both products.
<?php
use Atom\Database\DatabaseConnection;
use Atom\Database\Seeder\Seeder;
use Atom\Database\Sql\Query;
return new class extends Seeder
{
public function run(DatabaseConnection $db): void
{
$db->execute(Query::insert("categories")->values(["name" => "Lighting"]));
$categoryId = (int) $db->lastInsertId();
foreach (["Desk lamp" => 24, "Floor lamp" => 32] as $name => $price) {
$db->execute(Query::insert("products")->values([
"name" => $name,
"price" => $price,
"category_id" => $categoryId,
]));
}
}
};
Apply the schema with php atom migrate, then add the sample rows with php atom db:seed. The seed command runs discovered seeders each time, so this insert-only example adds another set of rows if rerun.
Roll back the migration
Use php atom migrate:status to see which migrations have run. php atom migrate:rollback rolls back the latest batch by default and calls down() on the migrations in that batch. For this migration, that drops both tables and deletes their rows, including seeded data.