使用Laravel模型过滤数据透视表数据 [英] Filtering pivot table data with Laravel models

查看:83
本文介绍了使用Laravel模型过滤数据透视表数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个表(这只是一个示例):

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)

以及相应的laravel模型:

And the corresponding laravel models:

   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);

每个用户对象将具有与之对应的所有角色的列表.我希望此列表仅包含主要角色.是否可以通过查询执行任何操作,而无需对$ users数组进行后处理?

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 = User::with(array('roles' => function($query)
{
    $query->where('primary', 1); 
}))->find(1);

这篇关于使用Laravel模型过滤数据透视表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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