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?
from Newest questions tagged laravel-5 - Stack Overflow http://bit.ly/2pR6MMc
via IFTTT
Aucun commentaire:
Enregistrer un commentaire