LoginSignup
35
39

More than 5 years have passed since last update.

Laravelで多対多の中間テーブルを用いたDBの作り方と使い方

Last updated at Posted at 2014-09-28

以下のチュートリアルで紹介されている基本的な使い方を抜粋し、まとめたものです。
http://daylerees.com/codebright/eloquent-relationships

0.DB構造について

DB構造は以下を想定します。
accountspostsが多対多になっているので、account_postという中間テーブルを用いて関係を表現しています。

スキーマ
accounts
 -id
 -name
posts
 -id
 -url
account_post
 -account_id
 -post_id

1.スキーマビルダーでテーブルを作成する

スキーマビルダーでテーブルを作成するためにマイグレーションの準備を行います。

# php artisan migrate:make CreateTables;

上記に示したテーブルを作成するよう、マイグレーションの定義を以下のように行います。
# vim app/database/migrations/**CreateTables.php

**CreateTables.php
Schema::create('accounts', function($table){
                        $table->increments('id');
                        $table->string('name', 64);
                        $table->timestamps();
                });

                Schema::create('posts', function($table){
                        $table->increments('id');
                        $table->string('url', 128);
                        $table->timestamps();
                });

                Schema::create('account_post', function($table){
                        $table->integer('account_id')->unsigned();
                        $table->foreign('account_id')->references('id')->on('accounts');
                        $table->integer('post_id')->unsigned();
                        $table->foreign('post_id')->references('id')->on('posts');
                });

実行すると、テーブルが作成されます。
# php artisan migrate

2.モデルクラスを作成する

次にEloquentモデルを作成します。作成するのは、accountモデルとpostモデルです。
多対多のモデルとなるので、お互いのクラスにお互いについて、belongsToManyメソッドを加えることにより、多対多を表現出来ます。中間テーブルについては、モデルは必要無いようです。

Account.php
<?php
class Account extends Eloquent{
        public function posts(){
                return $this->belongsToMany('post');
        }
}
Post.php
<?php
class Post extends Eloquent{

        public function accounts(){
                return $this->belongsToMany('account');
        }
}

3.テストする

ここまで来ればあとは使うだけです。
この例では、簡単にテストするため、DBにデータを挿入する処理をroutes.phpに書いてみます。

routes.php
Route::get('test', function(){
        $account = new Account;
        $account->name = 'test1';
        $account->save();

        $post = new Post;
        $post->url = 'http://go.jp';
        $post->save();

        $account->posts()->save($post);
        return 'test';
});
35
39
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
35
39