Search code examples
laravelbelongs-to

laravel 5.2 work with belongs to with two different queries


I have write down this query

Controller
$data = User::where('name',$name)->with('country');

In User model

function country () {
    return $this->belongsTo('App\Country');
}

In view

echo $data->country->name;

It is working fine but it run 2 queries :(

 Select * from user where name = "xyz"
 Select * from country where id = "745"

I want to stop this, I want to fetch data with one query only. Join is the solution, Is any other solution for this?


Solution

  • Unfortunately this is the way Eloquent works. It uses two queries because it's a simpler task to initialise your models and to avoid column naming conflicts.

    If you are concerned about performance but still want some sort of querying tool, use the Query Builder shipped with Laravel.

    To answer your question, joins will be your best bet.