Search code examples
laraveleloquentlaravel-5.3

Laravel running multiple queries instead of join in Eloquent


I am trying to run join between my pages table and users table. Means one user can create multiple pages and in pages table created_by column belongs to my users table column id.

Table Structure:

---------------------------------------------
  id  | page_title | page_desc | created_by |    
---------------------------------------------
  1   |  Testing   | Descripti |      1     |
---------------------------------------------
  2   |  New Page  | Desc      |      2     |

User table

-------------------------------------------
 id  | name  | email | pass | created_at |
-------------------------------------------
 1   |   A   | [email protected] | 123  | 2017-10-21 |
-------------------------------------------
 2   |   B   | [email protected] | 123  | 2017-10-21 |

in my Page model i used:

public function createdBy(){
    return $this->belongsTo('App\User','created_by','id');
}

now when i am trying to get the data with:

$model = Page::all()
foreach($model as $key => $value){

     echo $value->createdBy->name."<br/>";
}

laravel generating multiple queries to get name of each user is that any way to run the join instead of multiple queries?


Solution

  • You're running into the N+1 problem. You need to eager load your relationship to resolve this. You can read more on eager loading here.

    Use the with() method on the page query to eager load all the related user records for each page:

    $model = Page::with('createdBy')->get();
    foreach ($model as $key => $value) {
        echo $value->createdBy->name."<br/>";
    }
    

    This will now only run 2 queries: one to get all the pages, and one to get all the users related to each page.