LoginSignup
13
15

More than 5 years have passed since last update.

Laravel5 の Eloquent 多対多中間テーブルまとめ自分用

Last updated at Posted at 2015-02-23
Group *--* User

1つのグループには複数のユーザが所属できて
1人のユーザがいろんなグループに所属できるみたいなやつ

database/migrations/create_pivot_tables.php
Schema::create('group_user', function($table){
    $table->increments('id');
    $table->integer('group_id')->unsigned();
    $table->foreign('group_id')->references('id')->on('groups');
    $table->integer('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
    $table->unique(array('group_id', 'user_id'));
});

中間テーブル名はアルファベット順に並べる

Group.php
public function users(){
    return $this->belongToMany('hoge\User');
}

これでbelongToMany型が返ってくるねん

$users = $group->users();
$men = $users->where('gender', '=', 'man');

まだSQL実行されてないのでさらに条件追加したりできる

$results = $men->getResults();

getなんとか() 系のメソッドを実行するとSQL実行される

$userIds = $group->users()->getRelatedIds();

IDほしいだけなら belongToMany::getRelatedIds()

多対多の場合は逆もいっしょ

13
15
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
13
15