Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'
    ]
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading