多対多のテーブル構築は、必須。
しかし、非常に分かりづらい。
ということで極力シンプルにまとめた。
・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!