1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🚀 Laravelで最小のECサイトをDDDで作る!(マイグレーション編)

Posted at

こんにちは!Laravel×DDDシリーズ第6弾です😊 これまでドメイン設計を進めてきましたが、いよいよ実際にLaravelのプロジェクトを作成して、データベースの構造を整備していきましょう。

マイグレーションを使うことで、データベースをコードベースで管理できます。これでDDDの設計が実際のDB構造と一致しますよ✨

📌 マイグレーションファイルの構成

今回作成するマイグレーションファイルは以下の通りです。

  • ユーザー(users)
  • 商品(products)
  • カート(carts)
  • 注文(orders)

① ユーザーテーブルのマイグレーション

ユーザー情報を管理します。

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

② 商品テーブルのマイグレーション

商品情報を管理します。

public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->integer('price');
        $table->integer('stock');
        $table->timestamps();
    });
}

③ カートテーブルのマイグレーション

ユーザーごとのカートを管理します。カート内の商品情報はJSON形式で管理します。

public function up(): void
{
    Schema::create('carts', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id')->unique();
        $table->json('items');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
    });
}

④ 注文テーブルのマイグレーション

注文情報と注文された商品内容をJSON形式で管理します。

public function up(): void
{
    Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->string('status')->default('pending');
        $table->json('items');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->cascadeOnDelete();
    });
}

📖 マイグレーションの実行方法

マイグレーションファイルを作成したら、以下のコマンドで実際にDBへ反映しましょう。

php artisan migrate

これで、設計したドメインとデータベースの構造が完全に一致するようになります!

🎯 マイグレーションを使うメリット

  • データベース構造が明確で再現性が高まる
  • ドメイン設計に忠実なDB構造になる
  • 変更管理が簡単になり、チーム内で共有しやすくなる

これでDDD設計から実際の実装への準備が整いましたね!次回は具体的なリポジトリの実装を進めていきましょう✨😊

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?