【发布时间】:2015-05-15 14:21:36
【问题描述】:
我有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');
}
}
我需要找到只属于一楼的地方。 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
【问题讨论】:
-
通过
whereHas生成的查询有什么问题? -
问题在于它是带有聚合计数()函数的奇怪查询。也许,只是也许,引擎 mysql 后面的那个把它翻译成简单的加入(或者加入这个,我真的不知道)。是否等于我提供的加入方法?
-
问题是,在 Laravel 中,只有在需要时才会发生连接。它在每个步骤中执行最有效的请求。在这种情况下,由于不需要连接,因此不会执行连接,而是使用
count()。如果您只是为了提高效率而这样做,那么您要么过度优化,要么不应该使用 Eloquent,因为它速度极慢且占用大量资源。
标签: php laravel eloquent laravel-5