以下のチュートリアルで紹介されている基本的な使い方を抜粋し、まとめたものです。
http://daylerees.com/codebright/eloquent-relationships
0.DB構造について
DB構造は以下を想定します。
accounts
とposts
が多対多になっているので、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
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
メソッドを加えることにより、多対多を表現出来ます。中間テーブルについては、モデルは必要無いようです。
<?php
class Account extends Eloquent{
public function posts(){
return $this->belongsToMany('post');
}
}
<?php
class Post extends Eloquent{
public function accounts(){
return $this->belongsToMany('account');
}
}
3.テストする
ここまで来ればあとは使うだけです。
この例では、簡単にテストするため、DBにデータを挿入する処理を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';
});