![](/img/trans.png)
[英]How to set Eloquent relationship belongsTo THROUGH another model in Laravel?
[英]Execute whereIn on relationship through another model with eloquent
我正在Laravel 4中用Eloquent做一些棘手的(至少对我来说)技巧。为了细化页面,我需要获取一个或多个省份内的一种或多种类型的所有对象。 现在,我试图弄清楚如何使用Eloquent为我检索这些信息(假设有可能)。 我认为必须是这样的:
Object::whereIn('objectType', $objectTypeArray)->whereIn('cities.provinces.id', $provinceIdArray)->paginate(15);
那是行不通的,因为它Unknown column 'cities.provinces.id' in 'where clause'
。
使用以下模型来完成此任务:
省
class Province extends Eloquent
{
protected $table = 'provinces';
public function cities(){
return $this->hasMany('City');
}
}
市
class City extends Eloquent
{
protected $table = 'cities';
public function province(){
return $this->belongsTo('Province');
}
public function object(){
return $this->hasMany('Object');
}
}
宾语
class Object extends Eloquent
{
protected $table = 'objects';
public function city(){
return $this->belongsTo('City');
}
public function address(){
return $this->belongsTo('Address');
}
public function object_type(){
this->belongsTo('ObjectType');
}
}
对象类型
class OutgoingType extends Eloquent
{
protected $table = 'outgoing_types';
public function outgoing(){
return $this->hasMany('Object');
}
}
在此先感谢您的帮助,我已经尝试了好几个小时,但似乎无法找到一个可以正常工作的解决方案。
如果您想使用模型中指定的Eloquent关系,那么我认为您需要使用
Object::with
渴望加载关系( http://four.laravel.com/docs/eloquent#eager-loading )而不是
Object::whereIn
-> whereIn()需要有效的表列名称,因此有关citys.provinces.id不是有效列的错误,因为在您的citys表中,它可能是citys.provinces_id,而Object :: with允许您使用喜欢的
Object::with('city.province')->get().
用这种方法添加约束有点棘手,因为您需要执行以下操作
Object::with(array('city' => function($query)
{
$query->whereIn('city_id', $array);
}))->get();
另一种方法是坚持使用whereIn方法,并使用来自数据库查询构建器http://four.laravel.com/docs/queries#joins的一些更传统的联接
抱歉,以上只是指针,而不是实际的解决方案。
编辑
刚玩过,这似乎可以满足您的要求:
Object::whereIn('object_type_id', $object_type_array)->with(array('city' => function($query) {
$query->whereIn('province_id', $province_id_array);
}))->get();
以上取决于您的外键是object_type_id和province_id
第二编辑
一种更传统的方法是,仅获取具有正确省份的城市的对象,而不仅仅是从结果集中的对象中排除城市。
$objects = Object::join('cities', 'city_id', '=', 'cities.id')
->whereIn('objects.object_type_id', $object_type_array)
->whereIn('cities.province_id', $province_id_array)->get()
雄辩的对象关系可能有一种方法可以达到相同的结果,但此刻让我回避-联接方法可能反而更有效。
狭谷
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.