LoginSignup
1
2

More than 3 years have passed since last update.

laravel 5.7 多対多

Posted at

多対多のテーブル構築は、必須。
しかし、非常に分かりづらい。
ということで極力シンプルにまとめた。

・User 1 に 対して 複数のRole を持つ
・Role 1 に 対して 複数のUser を持つ

これが多対多。

まずはテーブルを作成

・users

id user_name
50014 ひでまん
50015 たろすけ
50017 ありか

・roles

id title
5 りんご
6 みかん

・role_user

中間テーブル。命名規則として、role と user をアルファベット順に並べ_で区切る

id user_id role_id
1 50014 6
2 50014 5
3 50017 5

model を作成

app\User.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //hoge2 以外のフィールドはすべて保存できる
    protected $guarded = ['hoge2'];


    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

}


app\Role.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    //hoge2 以外のフィールドはすべて保存できる
    protected $guarded = ['hoge2'];
}



以上。

で適当なコントローラーで
use App\User; をして、


$res = User::query()

    //ロールケーキを持っているユーザーのみ読み出す
//            ->has('roles')


    //ロールID5を持っているユーザーのみ読み出す
//            ->whereHas('roles', function ($q) {
//                $q->where('role_id',5);
//            })

    ->with('roles')//roles モデルも読み出す。
    ->where('id','>=',50014)//User.id が 50014 以上のユーザーのみ読み出す
    ->get();







//        ロールケーキを持っている場合はロールケーキも表示
foreach ($res as $v) {
    echo $v->id." : ".$v->user_name."<br>";
    if(count($v->roles) != 0){
        echo "<b>ロールケーキを持っています</b><br>";
        foreach ($v->roles as $s) {
            echo $s->id.":".$s->title."<br>";
        }
    }
}

これでOK!

1
2
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
1
2