Eloquent ORM 未使用关系获取数据 laravel

Eloquent ORM not fetching data using relationship laravel

我是 laravel 的新手,正在使用 Eloquent ORM。现在的问题是我正在尝试使用 with() 函数的关系来获取记录。现在这个问题是 eloquent 生成并应用了正确的查询但没有 returns 任何结果。但是,如果我在 mysql 上测试相同的生成查询,它就可以正常工作。

下面是本次涉及到的两个表:

属性: 编号,名称,locality_id

地区: id, name , type , adjoining

现在上面提到的表之间的关系是一对多的关系。

属性 型号:

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');
}

Eloquent 查询:

$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 中使用上面提到的查询,那么它 returns 数据但是与 Eloquent ORM 一起使用它 returns NULL。 请帮助..

刚刚将 locality_id 添加到 select 并且成功了。实际上 eloquent 就像你有 2 个包含相关项的数组并且你想匹配它们 - 如果其中一个没有外键,它指向另一个中的主键,那么你不能这样做. Eloquent 完全一样。

您必须始终 select 关系的两个键(很可能是一个模型上的 PK 和另一个模型上的 FK)。