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()
多対多の場合は逆もいっしょ