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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试