Laravel关系-数据透视表中的其他字段链接到其他模型 [英] Laravel Relationship - Additional fields in pivot table linking to additional models

查看:74
本文介绍了Laravel关系-数据透视表中的其他字段链接到其他模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将问题简化到了重点.我有三个表,分别是 users roles account .

I have simplified the problem to get to the point. I have three tables, users, roles, account.

通常,我会将User模型设置为与角色具有多对多关系,但我希望这些角色特定于每个帐户.因此,我在数据透视表中添加了一个附加字段.这是我拥有的表和字段;

Normally I would set up the User model to have a many to many relationships with roles but I want those roles to be specific to each account. So I have added an additional field to the pivot table. Here are the tables and fields that I have;

用户"表

|—————————

| id | name |

|—————————

| 1 | Bob    |

| 2 | Jim     |

| 3 | Fred   |

|—————————

角色"表

|—————————

| id | title |

|—————————

| 1 | Administrator    |

| 2 | Manager           |

| 3 | Approver           |

|—————————

帐户"表

|—————————

| id | name |

|—————————

| 1 | ABC Company    |

| 2 | XYZ Shipping     |

| 3 | KLM Transport   |

|—————————

然后我有了数据透视表 role_user 以及该帐户的另一个数据透视字段;

I then have the pivot table role_user with an additional pivot field for the account;

|—————————

| role_id | user_id | account_id

|—————————

| 1         | 3           |  1

| 2         | 2           |  1

| 3         | 2           |  3

| 3         | 1           |  2

|—————————

在建立多对多关系时,我已经在belongsToMany函数上使用了 withPivot 函数.这使我可以使用 $ user-> roles-> pivot-> account_id 获取信息,但我需要的是能够获得该公司的名称.它传递给刀片模板的全部是数据透视表中的ID,而不是将其链接到实际的Account模型.

I have used the withPivot function on the belongsToMany function when setting up the many to many relationships. This allows me to get the information using $user->roles->pivot->account_id but what I need is to be able to get the name of that company. All it’s passing to the blade template is the id from the pivot table and not linking that to an actual Account model.

Eloquent是否有办法以与原始关系相同的方式获取整个模型?

Is there a way with Eloquent to get this entire model in the same way as the original relationship?

推荐答案

创建自定义数据透视模型

use Illuminate\Database\Eloquent\Relations\Pivot;

class RoleUserAccountPivot extends Pivot
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

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

    public function account()
    {
        return $this->belongsTo(Account::class);
    }
}

更新您的belongsToMany关系

Bellow是具有 User :: roles 关系

class User //extends...
{
    public function roles()
    {
        return $this->belongsToMany(Role::class, /*other parameters*/)->using(RoleUserAccountPivot::class)->withPivot('account_id');
    }
}

用法

$user->roles->first()->pivot->account // returns Account model

希望有帮助.

参考链接:

有关自定义枢轴的Laravel文档

这篇关于Laravel关系-数据透视表中的其他字段链接到其他模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆