我正在与Laravel和雄辩/MySQL一起做一个项目。
我想知道如何处理与三个表(用户、商人、角色)之间的多对多关系。
有什么最佳做法可以遵循吗?
我怎样才能让所有的商家都有一个特定的角色呢?
谢谢你的帮助
这是我目前的结构:
Users
-------------------------------
| id | first_name | last_name |
-------------------------------Merchants
-------------------
| id | trade_name |
-------------------Roles
-------------------------
| id | name | hierarchy |
-------------------------merchant_user_role
-----------------------------------
| merchant_id | user_id | role_id |
-----------------------------------商人模型
<?php
class Merchant extends Model
{
public function users()
{
return $this->belongsToMany('App\User', 'merchant_user_role')
->withPivot('role_id')
->withTimestamps()
->orderBy('first_name', 'asc');
}
}用户模型
<?php
class User extends Model
{
public function merchants()
{
return $this->belongsToMany('App\Merchant', 'merchant_user_role')
->withPivot('role_id')
->withTimestamps()
->orderBy('trade_name', 'asc');
}
public function roles()
{
return $this->belongsToMany('App\Role', 'merchant_user_role')
->withTimestamps();
}
}角色模型
<?php
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User')->withTimestamps();
}
}发布于 2019-09-24 11:17:37
$merchants = $user->merchants()->where('role_id', $some_role_id)->get();https://stackoverflow.com/questions/58078364
复制相似问题