加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 19:49:29 所属栏目:大数据 来源:网络整理
导读:假设我有三个表(这只是一个例子): users user_id usernameroles role_id nameuser_roles user_id role_id primary (boolean) 和相应的laravel模型: class User extends Eloquent { public function roles() { return $this-belongsToMany('Role')-withPivo
假设我有三个表(这只是一个例子):
users
   user_id
   username

roles
   role_id
   name

user_roles
    user_id
    role_id
    primary (boolean)

和相应的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');
         }
   }

我想获得所有用户的列表,但只返回返回对象中的主要角色.
如果我使用类似的东西:

$users = User::with('roles')->find(1);

每个用户对象都将包含与其对应的所有角色的列表.我希望此列表仅包含主要角色.有没有办法从查询中执行此操作,而无需后处理$users数组?

请尝试以下方法:
$users = User::with(array('roles' => function($query)
{
    $query->where('primary',1); 
}))->find(1);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读