[英]Laravel Eloquent: filtering model by relation table
我有places
和locations
表。 這個地方可能有很多位置。 位置屬於地方。
地點: 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');
}
}
我需要找到僅屬於1樓的地方。 select * from places inner join locations on places.id = locations.place_id where locations.floor = 1
口才應該如何做?
是否存在類似於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
這行不通嗎?
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。
我沒有嘗試過,但是您渴望加載並且可以有一個條件:
$places = Place::with(['locations' => function($query)
{
$query->where('floor', '=', 1);
}])->get();
嘗試這個 :
Place::join('locations', 'places.id', '=', 'locations.place_id')
->where('locations.floor', 1)
->select('places.*')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.