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.

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度