在Laravel中,如何从数据透视表访问数据? [英] In Laravel, how can I access data from a pivot table?

查看:62
本文介绍了在Laravel中,如何从数据透视表访问数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我执行错误.也许我在做我不应该做的事情,但是从概念上讲,我认为我还可以.

Maybe I'm implementing wrong. Maybe I'm doing things I'm not supposed to do, but conceptually I think I'm okay.

我有两个模型,一个是Users,另一个是Communities,由于这是多对多的关系,因此我需要一个中间表,Laravel称它们为数据透视表.根据Laravel的建议,它被命名为communities_users

I have two models, one is Users, other is Communities, and since it is a many to many relationship I need an intermediate table, Laravel calls them a pivot table. According to Laravel recommendations it is named communities_users

通常,数据透视表仅包含主表的ID.但是我需要更多数据.检查此图像,完成迁移以匹配此图:

Normally, the pivot tables only contain the id's to the main tables. But I need a bit more data. Check this image, the migrations are done to match this diagram:

我在数据透视表中有一个role.假设某个用户属于两个社区,一个作为社区的总裁,另一个作为成员.

Here I have a role in the pivot table. Lets say a user belongs to two communities, one as community's president, other as a member.

当然,president将具有比member更多的功能,例如,他可以接受pending人成为member人,或者他可以将成员提升为deputy状态大概...

Of course the president will have more capabilities than the member, for example, he can accept a pending person to become a member person, or he can promote a member to a deputy status or so...

现在可以说我想获得给定社区中具有deputy角色的人员的姓名.通过连接三个表并应用where('communities_users.role', 'deputy')

Now lets say I want to get the names of the people with deputy role on a given community. I can easily do that using the Query Builder, by joining the three tables and applying where('communities_users.role', 'deputy'),

现在,如果我想使用ORM并获得整个User模型怎么办?

Now, what if I want to use the ORM and get the whole User model?

我想在社区中使用某个功能,以便为我提供给定roleusers,也许是:

I'd like to have a function on the Community so it gives me the users of a given role, maybe:

public function users($role) {
    ...
}

所以我可以做类似的事情:

So I can do things like:

$community = Community::find($id);
foreach ($community->users('deputy') as user) {
    ...
    echo user->name; // or whatever
    ...
}

有可能吗?怎么样?

推荐答案

隐藏在部分:

Hiding under the Many To Many section of the Eloquent relationship docs:

通过中间表列过滤关系

在定义关系时,还可以使用wherePivotwherePivotIn方法过滤由belongsToMany返回的结果:

Filtering Relationships Via Intermediate Table Columns

You can also filter the results returned by belongsToMany using the wherePivot and wherePivotIn methods when defining the relationship:

return $this->belongsToMany('App\Role')->wherePivot('approved', 1);

return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

假设您的社区模型已经为用户设置了belongsToMany关系,那么您应该能够执行以下操作:

Assuming your Communities model already has a belongsToMany relationship set up for Users, you should be able to do something like:

$deputies = $community->users()
    ->wherePivot('role', 'deputy') // or equivalent value
    ->get();

这篇关于在Laravel中,如何从数据透视表访问数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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