Search code examples
laraveleloquenteloquent-relationship

Laravel many to many and hasMany, N+1


I got a model Event that has many private classes

  public function privateclasses()
  {
    return $this->hasMany(Privateclass::class);
  }

This is working perfect


Model Privateclass and User is connected in table "privateclass_user" with foreign key "privateclass_id" and "user_id".

In model Privateclass.php:

public function users()
  {
    return $this->belongsToMany(User::class);
  }

This is also working, but when I get the event the query count is high. How do I Eager Load this?

$event = Event::with('users')->get(); <-- NOT WORKING

In short: I want all users connected to privateclass that belongs to an Event.


Solution

  • https://laravel.com/docs/9.x/eloquent-relationships#nested-eager-loading

    To eager load a relationship's relationships, you may use "dot" syntax.

    Looks like you need:

    Event::with('privateclasses.users')
    

    or:

    Event::with([
        'privateclasses' => [
            'users'
        ]
    ])