问题描述
我有一个查询,我想使用Laravel查询构建器添加一个集合。
Hotel::addSelect([
'selectableLocations' => AllLocations::orderBy('name')->get()
])
->with('location')
->get();
好吧,这返回:
sqlSTATE [HY093]:无效的参数编号:混合的命名和位置参数(sql:从
[{"id":1,"name":"John Avenue"},{"id":4,"name":"Ontirio Village"},{"id":2,"name":"Rovie"},{"id":3,"name":"Movie Lot"}]
中选择dogs
限制100偏移0)
我知道这看起来像是一种反模式,但是我需要它的原因是因为我有一个数据表,并且想显示一个AllLocations的选择(下拉列表),以便用户可以更改数据表。
我的想法是我可以$dog->selectableLocations
查看所有位置。因为如果我不这样做,它将单独查询每一行。
有办法吗?
如果我能做到这一点,那将是完美的。
$selectableLocations = AllLocations::get();
$hotels = Hotel::addSelect([
'selectableLocations' => $selectableLocations
])
->with('location')
->get();
解决方法
编辑:
因为如果我不这样做,它将单独查询每一行。
由于您主要关心的是多个查询,因此,如果实现某种缓存,则可以避免数据库调用。为什么不将列表作为自定义属性包括在内,从缓存中进行负载收集?像这样:
public function getAllLocationsAttribute()
{
return Cache::remember('all_locations',30,function(){ //add remove seconds as required
return AllLocatiobs::get();
});
}
如何合并这两个集合?
$hotels = Hotel::get();
$selectableLocations = AllLocations::get();
$hotels->put('selectableLocations',$selectableLocations);
现在,$hotels->selectableLocations
将是AllLocations的集合。