我有一个Laravel 6应用程序。我想用雄辩的方式只收集那些敬业度得分等于true的员工。问题是,如何在函数结果上应用子句而不在 Eloqunt 中进行第二次选择?例如,像这样:whereavgSELECT `employees`.*, AVG(responses.text_answer) > 4.6 AS engagedFROM `employees`INNER JOIN `responses` AS `responses`ON `responses`.`employee_id` = `employees`.`id`INNER JOIN `survey_questions` AS `surveyQuestions`ON `surveyQuestions`.`id` = `responses`.`survey_question_id`INNER JOIN `questions` AS `questions`ON `questions`.`id` = `surveyQuestions`.`question_id`WHERE engaged = 1 AND `questions`.`question_type_id` = '6S'GROUP BY `employees`.`id`但问题是这里的WHERE条件无法识别,MySQL显示:engaged“where 子句”中的“已参与”列未知我雄辩的一部分陈述是这样的:public function engaged() { return $this->relatedToMany(QuestionType::class, function(Builder $query){ if(!$this->joined($query, 'responses')){ $query->join( 'responses AS responses', 'responses.employee_id', '=', 'employees.id', 'inner' ); } if(!$this->joined($query, 'survey_questions')){ $query->join( 'survey_questions AS surveyQuestions', 'surveyQuestions.id', '=', 'responses.survey_question_id', 'inner' ); } if(!$this->joined($query, 'questions')){ $query->join( 'questions AS questions', 'questions.id', '=', 'surveyQuestions.question_id', 'inner' ); } $query->where('questions.question_type_id', '6S'); $query->select('employees.*', \DB::raw('AVG(`responses`.`text_answer`) >= 4.6 AS `engaged`')); $query->groupBy('employees.id'); }); }
1 回答
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
不能将条件应用于聚合函数。数据库首先计算子句,然后聚合。WHEREWHERE
相反,您可以对此使用子句(在子句之后计算)。HAVINGGROUP BY
因此,您需要更改以下内容:
WHERE
engaged = 1 AND `questions`.`question_type_id` = '6S'
GROUP BY
`employees`.`id`
自:
WHERE
`questions`.`question_type_id` = '6S'
GROUP BY
`employees`.`id`
HAVING
engaged = 1
在Lavare中,这应该看起来像这样:
$query->where('questions.question_type_id', '6S');
$query->select('employees.*', \DB::raw('AVG(`responses`.`text_answer`) >= 4.6 AS `engaged`'));
$query->groupBy('employees.id');
$query->havingRaw('engaged = 1');
- 1 回答
- 0 关注
- 51 浏览
添加回答
举报
0/150
提交
取消