Я работаю над проектом с Laravel и Eloquent / 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();
}
}