varovas's avatar

Can Eloquent query with() return only array without loading models?

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();
0 likes
5 replies
Ben Taylor's avatar

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')
krisi_gjika's avatar

how do you intend to display 3000 questions x 10 exams to your users?

1 like
varovas's avatar

Replying to both of above. I am building exams list for users. Each exam has title, total questions count and number of how many questions current user have already answered in each exam/practice.

krisi_gjika's avatar
Level 14

@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()
1 like

Please or to participate in this conversation.