Using the Laravel Eloquent ORM system I have created the following models:
/** * @property int $id */ class Category extends Model { public function questions() { return $this->hasMany(Question::class); } } /** * @property int $id * @property int $category_id */ class Question extends Model { public function answers() { return $this->hasMany(Answer::class); } } /** * @property int $id * @property int $question_id */ class Answer extends Model {} Now I am trying to eager load the following values:
- All categories
- The amount of questions per category
- The amount of answered questions per category
I have solved both 1 and 2 using this code:
$categories = Category ::withCount('questions') ->get(); $vars = ['categories' => $categories]; For the third value I tried something like this (which does not work):
$categories = Category ::withCount(['questions', 'questions as answered_questions' => function ($query) { $query->select() ->from('answers') ->whereRaw('answers.question_id = questions.id'); }]) ->get(); How can I efficiently calculate the amount of questions having one or more answers?