Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel Eloquent:选择相关表中有x的位置,但从相关表中排除某些行_Php_Mysql_Database_Laravel_Eloquent - Fatal编程技术网

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

Php Laravel Eloquent:选择相关表中有x的位置,但从相关表中排除某些行,php,mysql,database,laravel,eloquent,Php,Mysql,Database,Laravel,Eloquent,我试图从包含“用户组”及其相关用户的数据库返回一个集合。但是,我希望选择标准基于相关表中的用户是否接受过培训。如果是这种情况,我希望将该行/条目从最终集合中排除 基本上,我想: 返回“GreenGroup”类型的所有组,其中至少有一名相关员工未经培训,并在表中仅显示未经培训的员工 这样它将返回如下对象: 0: { id: 2, group: GreenGroup, size: 4, employees: { 0: {name: 'Jane', isTrained: 0}, 1: {

我试图从包含“用户组”及其相关用户的数据库返回一个集合。但是,我希望选择标准基于相关表中的用户是否接受过培训。如果是这种情况,我希望将该行/条目从最终集合中排除

基本上,我想:

返回“GreenGroup”类型的所有组,其中至少有一名相关员工未经培训,并在表中仅显示未经培训的员工

这样它将返回如下对象:

0: {
id: 2,
group: GreenGroup,
size: 4,
employees: {
   0: {name: 'Jane', isTrained: 0},
   1: {name: 'Jeremy', isTrained: 0}
  }
}
但现在,它正在查找GreenGroup,但返回该组中的所有用户。我正在寻找一种在查询生成器中排除它们的方法。到目前为止,我的情况如下:

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

  return json_encode($results);

有没有办法排除querybuilder中的关系表项?还是我被迫(当我在我的网站上循环并显示它们时)编写逻辑来检查它们是否经过培训?

您需要像下面提到的那样更改查询:

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

   return json_encode($results);
您提到的查询将始终返回所有成员,因为您在其中设置了条件wherehasnotin with

您编写的查询主要用于获取具有非训练成员的所有组(为此,您需要删除where('group','=','GreenGroup')),但您需要相反的内容,因此需要在中设置条件