Laravel Eloquent for pivot table with 2 foreign keys to a table and 1 foreign key to another table

Laravel Eloquent for pivot table with 2 foreign keys to a table and 1 foreign key to another table

我有 tables 如下,其中 role_idroles table 的外键,user_idsetter_idusers table.

的外键
table 1:
+---------------------+
| users               |
+---------------------+
| id                  |
| name                |
| email               |
| password            |
+---------------------+

table 2:
+---------------------+
| roles               |
+---------------------+
| id                  |
| name                |
+---------------------+

pivot table:
+---------------------+
| role_user           |
+---------------------+
| role_id             |
| user_id             |
| setter_id           |
+---------------------+

我定义的模型:

用户模型:

class User extends Model
{
    public $timestamps = false;
    
     public function roles()
     {
         return $this->belongsToMany(Role::class);
     }
}

榜样:

class Role extends Model
{
    public $timestamps = false;
    
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

如何更改我的模型以便获得如下所示的数据?

user -> roles -> setter : 用户及其角色以及用户

的每个角色的setter

谢谢...

您可以更新 belongsToMany 调用以在枢轴上也包含 setter_id,然后通过 ->pivot->setter_id 访问它并使用该 ID 检索模型。

return $this->belongsToMany(Role::class)->withPivot('setter_id');

或者(我个人会这样做)您可以 define a custom pivot model,并在那里创建一个 setter() 关系,这样您就可以直接从数据透视表中检索模型。

您将永远无法通过在角色集合中调用来访问 setter。

这是错误的:

$user->roles->setter

让我们看一个可行的例子:

foreach($user->roles as $role)
{
    dd($role->pivot->setter)
}

要做到这一点,您需要更改模型以反映如下内容:

用户

class User extends Model
{
    public $timestamps = false;
    
     public function roles()
     {
         return $this->belongsToMany(Role::class)
            ->using(UserRolePivot::class)
            ->withPivot([
                'role_id',
                'user_id',
                'setter_id',
            ]);
     }
}

角色

class Role extends Model
{
    public $timestamps = false;
    
    public function users()
    {
        return $this->belongsToMany(User::class)
            ->using(UserRolePivot::class)
            ->withPivot([
                'role_id',
                'user_id',
                'setter_id',
            ]);
    }
}

枢轴

use Illuminate\Database\Eloquent\Relations\Pivot;

class UserRolePivot extends Pivot
{
    protected $fillable = [
        'role_id',
        'user_id',
        'setter_id',
    ];

    public function role()
    {
        return $this->belongsTo(Role::class , 'role_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class , 'user_id');
    }

    public function setter()
    {
        return $this->belongsTo(User::class , 'setter_id);
    }
}