我得到了一个调查表的设置,每个调查都有一些与自身相关的答案(一对多)。我想进行一个查询来计算每个surveyId的答案数,分别为parameter1 = 0和parameter1 = 1。
我试着这样做:
$surveysWithRepliesExposed = Survey::where('title', 'LIKE', "%$name%")
->with(array('surveyAnswerSets' => function($query){
$query->where('parameter1', 0)
->selectRaw('surveyId, count(*) as repliesExposed')
->groupBy('surveyId');
}))
->select($columns);
$surveysWithRepliesExposed = Survey::where('title', 'LIKE', "%$name%")
->with(array('surveyAnswerSets' => function($query){
$query->where('parameter1', 1)
->selectRaw('surveyId, count(*) as repliesControl')
->groupBy('surveyId');
}))
->select($columns);
但是现在我得到两个看起来几乎相同的集合:
{
"surveyId": 11,
"title": "A survey",
"startDate": "2015-04-16",
"endDate": "2015-04-30",
"survey_answer_sets": [
{
"surveyId": 11,
"repliesExposed": 212
}
]
}
另一个
{
"surveyId": 11,
"title": "A survey",
"startDate": "2015-04-16",
"endDate": "2015-04-30",
"survey_answer_sets": [
{
"surveyId": 11,
"repliesControl": 56
}
]
}
我如何合并这些以便
{
"surveyId": 11,
"title": "A survey",
"startDate": "2015-04-16",
"endDate": "2015-04-30",
"survey_answer_sets": [
{
"surveyId": 11,
"repliesExposed": 212
"repliesControl": 56
}
]
}
答案 0 :(得分:0)
我在朋友的帮助下解决了这个问题。
这段代码符合我的要求!
$surveys = Survey::leftJoin('SurveyAnswerSets', 'Surveys.surveyId', '=', 'SurveyAnswerSets.surveyId')
->select(
DB::raw(
"Surveys.surveyId,
Surveys.title,
Surveys.startDate,
Surveys.endDate,
sum(case when SurveyAnswerSets.isRefGroup = 0 then 1 else 0 end) repliesExposed,
sum(case when SurveyAnswerSets.isRefGroup = 1 then 1 else 0 end) repliesControl,
sum(1) repliesTotal"
)
)
->where('SurveyAnswerSets.isComplete', 1)
->where('Surveys.title', 'LIKE', "%$name%")
->where('Surveys.isTemplate', 0)
->groupBy('Surveys.surveyId')->get();