dsqdpn31467 2018-09-10 23:58
浏览 57
已采纳

Laravel Eloquent:选择相关表有x的位置,但从相关表中排除某些行

Im trying to return a collection from the database that houses a 'User Group' as well as its related users. However, I want the selection criteria to be based on whether or not a user in the related table is trained or not. If this is the case, I want that row/entry to be EXCLUDED from the final collection.

enter image description here

Essentially, I want to:

Return all groups of type 'GreenGroup' where at least one related employee is untrained, and show only untrained employees in the table.

Such that it would return an object like this:

0: {
id: 2,
group: GreenGroup,
size: 4,
employees: {
   0: {name: 'Jane', isTrained: 0},
   1: {name: 'Jeremy', isTrained: 0}
  }
}

But right now, it is finding the GreenGroup, but returning ALL users in that group. I am looking for a way to exclude them in the query builder. So far, this is what I have:

$results = Group::with(['employees'])->where('group', '=', 'GreenGroup')->whereHas('employees', function($query){
      $query->where('isTrained', '=', '0');
    })->get();

  return json_encode($results);

Is there a way to exclude relational table entries in the querybuilder? Or am I forced (when I loop through these and display them on my site) to write logic that checks if they're trained or not?

  • 写回答

1条回答 默认 最新

  • douxue7196 2018-09-11 00:17
    关注

    You need to change your query like I mentioned below:

     $results = Group::with(['employees' => function($query){
           $query->where('isTrained', '=', '0');
         }])->where('group', '=', 'GreenGroup')->get();
    
       return json_encode($results);
    

    The query which you mentioned will return always all the members because you set condition in whereHas not in with.

    The query you wrote is mainly used to get all the groups with nontrained members ( for this you need to remove where('group', '=', 'GreenGroup') ) but you want something opposite, so you need to set condition in With.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里