Laravel - select with relationship with one query

折月煮酒 提交于 2019-12-08 04:09:13

问题


I have a Person model. Each person may have zero or more cars:

class Person extends Model
{
    public function cars()
    {
        return $this->hasMany('App\Car');
    }
}

I wish to select and display all persons who have a ford with one running query. So i tried this:

$persons = Person::whereHas('cars', function ($query) {
    $query->where('mark', 'ford');
})->get();

foreach ($persons as $person) {
    foreach($person->cars()->get() as $car) {
        print $person->name . " has a " . $car->mark . $car->model
    } 
}

The $persons is gotten with one query, but inside the foreach loop $person->cars()->get() creates a new query for each person. How can i avoid this and get the needed car data with the first query?


回答1:


You have to add the mark filter to whereHas() and with():

$persons = Person::whereHas('cars', function ($query) {
    $query->where('mark', 'ford');
})->with(['cars' => function($query) {
    $query->where('mark', 'ford');
}])->get();



回答2:


The issue is in cars()

Use the below given snippet

foreach ($persons as $person) {
     foreach($person->cars as $car) 
       { 
         print $person->name . " has a " . $car->mark . $car->model
        } 
      }

When u do cars() it refers to model which execute another query. But when u use cars it only refers to collection which is already loaded.

Hope this helps




回答3:


it is worth examining : laravel Eager Loading

When used in this manner will come in a query relational data.

Example:

Person::with('cars')->get();

This code response: Person data with Person's Car data



来源:https://stackoverflow.com/questions/49563701/laravel-select-with-relationship-with-one-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!