Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

juanmb's avatar

Selecting columns with eager loading

I have the following Eloquent statement inside a model belongsToMany relationship

  public function degreesAndSchools()
  {
    return $this->belongsToMany(Course::class, 'courses_users')
      ->with(['degree'=>function($q){$q->select(['id','school_id','name']);}])
      ->with(['degree.school'=>function($q){$q->select(['id','name']);}])
      ->select(['name','degree_id']);
  }

What i want to do is to obtain only the columns mentioned in the select() methods. The thing is that I succeed with the courses and schools tables but not with the one in the middle (degrees). According to Debugbar, these are the SQL queries :

select * from `users` where `id` = '50' limit 1
select `name`, `degree_id`, `courses_users`.`user_id` as `pivot_user_id`, `courses_users`.`course_id` as `pivot_course_id` from `courses` inner join `courses_users` on `courses`.`id` = `courses_users`.`course_id` where `courses_users`.`user_id` = '50'
select * from `degrees` where `degrees`.`id` in ('1', '3', '9')
select `id`, `name` from `schools` where `schools`.`id` in ('2', '12')

Any clues?

0 likes
1 reply
juanmb's avatar
juanmb
OP
Best Answer
Level 6

The solution to my own question is that those two concatenated with() methods should be converted to a single call:

public function degreesAndSchools()
  {
    return $this->belongsToMany(Course::class, 'courses_users')
      ->with(['degree'=>function($q){$q->select(['id','school_id','name']);}],
             ['degree.school'=>function($q){$q->select(['id','name']);}])
      ->select(['name','degree_id']);
  }

Doh!

Please or to participate in this conversation.