Laravel-与一个查询建立关系 [英] Laravel - select with relationship with one query

查看:93
本文介绍了Laravel-与一个查询建立关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Person模型.每个人可能有零辆或更多的汽车:

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
    } 
}

$ persons是通过一个查询获得的,但是在foreach循环中,$ person-> cars()-> get()为每个人创建一个新查询.我该如何避免这种情况,并在第一个查询中获得所需的汽车数据?

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?

推荐答案

您必须将mark过滤器添加到whereHas()with():

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();

这篇关于Laravel-与一个查询建立关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆