所以我Subject
包含Stack
,其中包含Question
。对于每个问题,都有答案,我想在每个Stack
上计算答案,但我被卡住了。
这就是我正在尝试做的事情,这是我一直在努力解决的众多解决方案之一:
$subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();
return $subjects;
Subject
模型具有以下关系:
public function stack(){
return $this->hasMany(Stack::class);
}
如果我们看看Stack
关于如何建立关系的模型:
public function question(){
return $this->hasMany(Question::class);
}
public function answers(){
return $this->hasMany(Answers::class);
}
public function answersCount(){
return $this->answers()->selectRaw('answer, count(*) as aggregate')->groupBy('answer');
}
但是当我return $subjects
时,answer_count
为空。
"answers_count": []
这非常令人困惑,因为当我在SQL中运行相同的查询时,我得到非空结果。
select answer, count(*) as aggregate from `answers` where `answers`.`stack_id` in ('1', '6') group by `answer`
correct 9
wrong 4
那么我怎么能算出所有答案呢?和他们分组?
答案 0 :(得分:0)
试试这个,
$subjects = Subject::with(['stack.question', 'stack.answersCount'])->get();
$count = $subjects->answersCount->first()->aggregate;
//count varible will have the count now you can use it as you would like to
return $subjects;
可以找到进一步的挖掘here
答案 1 :(得分:0)
删除answersCount
关系 - 不再需要了,因为您可以使用withCount
方法:
$subjects = Subject::with([
'stack.question',
'stack' => function ($q) {
$q->withCount('answers');
}
])->get();
// then on each subject you can call stack->answers_count
$subjects->first()->stack->answers_count