我是laravel的新手并使用Eloquent ORM . 现在的问题是我正在尝试使用与with()函数的关系来获取记录 . 现在这个问题是eloquent生成并应用正确的查询但不返回任何结果 . 但是如果我在mysql上测试相同的生成查询比它工作正常 .
以下是涉及此的两个表:
属性:id,name,locality_id
地区:id,名称,类型,毗邻
现在上面提到的表之间的关系是一对多的关系 .
properties 模型:
protected $table = 'properties';
protected $guarded = array('id');
public function localityAreaAndCity() {
return $this->belongsTo('Locality','locality_id')
->leftjoin('localities as ls', function($join)
{
$join->on('localities.id', '=', 'ls.adjoining')
->where('localities.type', '=','area');
});
->select(array('localities.name as localityPrimaryName',
'localities.type as localityPrimaryType',
'ls.name as localitySecondaryName',
'ls.type as localitySecondaryType'));
}
地区模型:
public $timestamps = false;
protected $table = 'localities';
protected $guarded = array('id');
public function properties()
{
return $this->hasMany('Property');
}
雄辩查询:
$properties = Property::with('localityAreaAndCity')->get();
DB :: getQueryLog()结果:
select `localities`.`name` as `localityPrimaryName`, `localities`.`type` as `localityPrimaryType`, `ls`.`name` as `localitySecondaryName`, `ls`.`type` as `localitySecondaryType` from `localities` left join `localities` as `ls` on `localities`.`id` = `ls`.`adjoining` and `localities`.`type` = ? where `localities`.`id` in (?, ?, ?, ?, ?)
知道我是否在mysql中使用上面提到的查询然后它返回数据但是使用Eloquent ORM它返回NULL . 请帮忙..
1 回答
刚刚将locality_id添加到select中并且工作正常 . 实际上雄辩的作品就像你有2个带有相关项目的数组而你想要匹配它们 - 如果其中一个没有外键,那么指向另一个中的主键,则你不能这样做 . Eloquent完全一样 .
您必须始终选择关系的两个键(很可能是一个模型上的PK和另一个模型上的FK) .