skip to Main Content

I am using laravel 9 for my project with relation some tables

table types genders qualifications occupations
id id id id
name name name name
mains members pivot table : main_member
id id id
type_id main_id main_id
full_name full_name member_id
address

Models : Type (relation with table mains)

public function mains()
{
   return $this->hasMany(Main::class);
}

Models : Gender (relation with table members)

public function member()
{
   return $this->hasMany(Member::class);
}

Models : Qualification (relation with table members)

public function member()
{
   return $this->hasMany(Member::class);
}

Models : Occupation (relation with table members)

public function member()
{
   return $this->hasMany(Member::class);
}

Models : Occupation (relation with table members)

public function member()
{
   return $this->hasMany(Member::class);
}

— belongToMany relation —

Models : Main (relation with table members)

public function members()
{
   return $this->belongsToMany(Member::class)
}

I have already create controller : MainController

public function index()
{
   $this->data['warga'] = Main::with('members')->get();
   $this->data['title'] = 'Family list';
   return $this->adminTheme('family.index', $this->data);
}

With code above, I can retrieve record from table mains and also table members inside table mains.

The problem that I found is there are hundreds query at the same times (with 50 samples data in table mains and almost 100 datas in table members).

How can I implement eager loading to minimize query above.

Thank you for your help.

2

Answers


  1. How about pagination?

    Main::with('members')->paginate()
    
    Login or Signup to reply.
  2. You can do something like this

    Main::with('members' => function ($q) {
        // the realation you want, you can eager load from here
        // I am not sure if gender is in member model, its just for
        // example, you can adjust your relationship        
        $q->with('gender');  
    })->get()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search