简体   繁体   English

Laravel Eloquent:按关系表过滤模型

[英]Laravel Eloquent: filtering model by relation table

I have places and locations tables. 我有placeslocations表。 Place could have many locations. 这个地方可能有很多位置。 Location belongs to Place. 位置属于地方。

Place: id title 地点: id title

Location: id place_id floor lat lon 位置: id place_id floor lat lon

class Location extends Model {

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

}

And

class Place extends Model {

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

}

And i need to find places, that belongs only to 1st floor. 我需要找到仅属于1楼的地方。 select * from places inner join locations on places.id = locations.place_id where locations.floor = 1

How does it should be done in Eloquent? 口才应该如何做?

Is something similar to Place::where('locations.floor', '=', 1)->get() exists? 是否存在类似于Place::where('locations.floor', '=', 1)->get()

Yes, i know there is whereHas : 是的,我知道有whereHas

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

but it generates a bit complex query with counts: 但它会生成一个带有计数的复杂查询:

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

does not this works? 这行不通吗?

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

finally, any orm is not for database usage optimization, and it is not worth to expect nice sql's produced by it. 最后,任何orm都不是用于数据库使用优化的,也不值得期待它产生的漂亮的sql。

I haven't tried this, but you have eager loading and you can have a condition: 我没有尝试过,但是您渴望加载并且可以有一个条件:

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

}])->get();

Source 资源

Try this : 尝试这个 :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM