Not sure I totally understand what you want, but you can limit what you get with the with method. For example
->with('exam:id', 'exam.questions:id,exam_id')
Hi, I wonder if laravel can query related ids without loading models for these ids? I need all ids, because I am checking if user has any of that ids relations. Each exam can have several thousand related questions, so if there are for example 10 exams and each exam has 3000 questions, then laravel will load 30k models, which I think is not very good. Maybe I am wrong?
Example query:
$exams = $category
->exams()
->with(['exam' => function ($query) {
$query->withCount('questions')->with(['questions' => function($q) {
$q->select('question_id');
}]);
}])
->orderBy('sort_order', 'asc')
->get();
@varovas now this makes more sense, however for this you should not be loading models. I think you mean something like this:
Exam::query()
->assignedTo(auth()->user()) // custom scope relating users and assigned exams
->withCount([
'questions as exam_total_questions',
'questions as exam_user_answered_questions' => function (Builder $query) {
// count only questions that have an answer from this user
$query->whereHas('answers', function (Builder $query) {
$query->where('user_id', auth()->id());
});
},
])
->get()
Please or to participate in this conversation.