Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.
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()

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

kituneponyo
よわよわぷらぐらま いかに低い意識と技術でその場をどうにかごまかして乗り切るかばかり考えている(乗り切れない)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away