使用 Laravel 模型过滤数据透视表数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20759891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering pivot table data with Laravel models
提问by user1544110
Let's say I have three tables (this is just an example):
假设我有三个表(这只是一个例子):
users
user_id
username
roles
role_id
name
user_roles
user_id
role_id
primary (boolean)
And the corresponding laravel models:
以及相应的 Laravel 模型:
class User extends Eloquent {
public function roles() {
return $this->belongsToMany('Role')->withPivot('primary');
}
}
class Role extends Eloquent {
public function users() {
return $this->belongsToMany('User')->withPivot('primary');
}
}
I want to get a list of all users, but with only the primary roles in the returned object. If I use something like:
我想获得所有用户的列表,但只有返回对象中的主要角色。如果我使用类似的东西:
$users = User::with('roles')->find(1);
Each user object will have a list of all the roles corresponding to it. I want this list to contain only the primary roles. Is there any way to do this from a query, without post processing the $users array?
每个用户对象都有一个与其对应的所有角色的列表。我希望此列表仅包含主要角色。有没有办法从查询中做到这一点,而无需对 $users 数组进行后期处理?
回答by Dkok
I'd suggest you create an extra method in your User model like this:
我建议您在 User 模型中创建一个额外的方法,如下所示:
public function primaryRoles() {
return $this->roles()->wherePivot('primary', true);
}
Then use something like:
然后使用类似的东西:
$users = User::with('primaryRoles')->find(1);
Also, the "Eager Load Constraints" section in the documentationmight be relevant.
此外,文档中的“Eager Load Constraints”部分可能是相关的。
回答by Anam
Try the following:
请尝试以下操作:
$users = User::with(array('roles' => function($query)
{
$query->where('primary', 1);
}))->find(1);