Laravel Eloquent:按关系表过滤模型

时间:2015-05-15 14:21:36

标签: php laravel eloquent laravel-5

我有placeslocations个表格。 地方可能有很多地方。地点属于Place。

地点: id title

位置: id place_id floor lat lon

class Location extends Model {

    public function place()
    {
        return $this->belongsTo('App\Place');
    }

}

class Place extends Model {

    public function locations()
    {
        return $this->hasMany('App\Location');
    }

}

我需要找到只属于一楼的地方。 select * from places inner join locations on places.id = locations.place_id where locations.floor = 1

如何在Eloquent中完成?

类似的东西 Place::where('locations.floor', '=', 1)->get()存在?

是的,我知道有whereHas

Place::whereHas('locations', function($q)
{
    $q->where('floor', '=', 1);
})->get()

但它会生成一个带有计数的复杂查询:

select * from `places` where (select count(*) from `locations` where `locations`.`place_id` = `places`.`id` and `floor` = '1') >= 1

3 个答案:

答案 0 :(得分:0)

这不起作用吗?

class Location extends Model {

    public function place()
    {
        return $this->belongsTo('App\Place');
    }

}

$locations = Location::where('floor', '=', 1);
$locations->load('place'); //lazy eager loading to reduce queries number
$locations->each(function($location){ 
    $place = $location->place
    //this will run for each found location 
});    

最后,任何orm都不是用于数据库使用优化,并且不值得期待由它生成的好的sql。

答案 1 :(得分:0)

我还没试过这个,但你已经急切加载了,你可以有条件:

$places = Place::with(['locations' => function($query)
{
    $query->where('floor', '=', 1);

}])->get();

Source

答案 2 :(得分:0)

试试这个:

Place::join('locations', 'places.id', '=', 'locations.place_id')
->where('locations.floor', 1)
->select('places.*')
->get();