在一个渴望加载的关系Laravel上返回计数

时间:2017-10-01 14:30:53

标签: php laravel laravel-5 eloquent

所以我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

那么我怎么能算出所有答案呢?和他们分组?

2 个答案:

答案 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