LoginSignup
5
5

More than 5 years have passed since last update.

データベースのスキーマとLaravelのマイグレーション 多対多の関係について

Last updated at Posted at 2015-10-03

はじめに

DBの多対多の関係について。
Laravelフレームワークについても少し話します。

多対多の関係 対照表とはそもそも...

多対多の関係では対照表というものが必要になります。
そもそも対照表とは、下記の図のarticle_tagsにあたるものです。

qiita1.png



なぜ対照表というものを用意しなけばいけないのか、ということを考えたことはあるでしょうか。
答えはDBの冗長性を排除するためです。

対照表がなかった場合、それぞれのテーブルに関係のあるテーブルのIDをもたせなければいけなくなります。
下記の図のように、できないことはないです。

qiita2.png



しかし、よく考えてみてください。もしもタグをもたないarticlesのレコードがあったとしましょう。
articlesテーブルのtag_idにはnullがをいれても良いですが、そもそもその列は不要ですよね。
つまり、冗長と言えます。
それを回避するために対照表というものが必要というわけです。

簡単に対照表を作れるLaravelのマイグレーション

Laravelフレームワークでも、勿論対照表を簡単に作成できます。

php artisan make:migration create_articles_table --create="articles"
php artisan make:migration create_tags_table --create="tags"

などとコマンドを打ちます。その後、database/migrations/2015-10-03-xxxxx_create_articles_table.phpのup()関数内を、

2015-10-03-xxxxx_create_articles_table.php
public function up()
{
    Schema::create('article' , function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->string('body');
    });
}

と記述。
database/migrations/2015-10-03-xxxxx_create_tags_table.phpのup()関数内を、

2015-10-03-xxxxx_create_tags_table.php
public function up()
{
    Schema::create('tags' , function(Blueprint $table){
        $table->increments('id');
        $table->string('name');
        $table->string('body');
    });
    Schema::create('article_tags',function(Blueprint $table)
    {
        $table->integer('article_id')->unsigned()->index();
        $table->foreign('article_id')->references('id')->on('article')->onDelete('cascade');
        $table->integer('tag_id')->unsigned()->index();
        $table->timestamps();

    });        
}

と記述し、php artisan migrateコマンドを打つとテーブルが作成されます。

5
5
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
5
5