简体   繁体   English

使用Laravel模型过滤数据透视表数据

[英]Filtering pivot table data with Laravel models

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数组?

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 documentation might be relevant. 此外, 文档中的“Eager Load Constraints”部分可能是相关的。

Try the following: 请尝试以下方法:

$users = User::with(array('roles' => function($query)
{
    $query->where('primary', 1); 
}))->find(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM