[英]Eloquent ORM not fetching data using relationship laravel
我是laravel的新手,并且使用了雄辩的ORM。 现在的问题是我正在尝试使用与with()函数的关系来获取记录。 现在的问题是,雄辩地生成并应用正确的查询,但不返回任何结果。 但是,如果我在mysql上测试相同的生成查询,则效果很好。
以下是其中涉及的两个表:
属性:id,name,locality_id
地点:ID,名称,类型,相邻
现在,上述表之间的关系是一对多关系。
物业型号:
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。 请帮忙..
只需将locality_id添加到选择中即可。 实际上有说服力的作品,例如您有2个包含相关项目的数组,并且想要将它们匹配-如果其中一个没有外键,而指向另一个中的主键,那么您将无法做到这一点。 口才是一样的。
您必须始终选择该关系的两个键(一种模型上最可能使用PK,另一种模型上最可能使用FK)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.