由于方法名称,hasOne() 不返回关系

hasOne() not returning relationships because of method name

我正在使用 laravel 5.3,我有与城市 table.

有 hasOne 关系的列表 table
public function city()
{
    return $this->hasOne('App\City', 'id', 'city_id');
}

在我看来

{{$listing->city->name}}

这导致错误

Trying to get property of non-object

但是当我将方法名称更改为城市以外的名称时,

public function foo()
{
    return $this->hasOne('App\City', 'id', 'city_id');
}

在我看来

{{$listing->foo->name}}

这个有效。

城市方法名称出现问题的原因是什么? 我在其他项目中从来没有遇到城市方法名称的问题。

您似乎在代码中的其他地方使用 city 作为对象的属性 - 它已经包含该值,因此使用该值而不是关系。

寻找一些设置了 $listing->city 值的地方,尝试 dd($listing->city) 寻找线索。如果您找不到它,post 一些您的代码,因为错误出在您目前 post 编辑的其他地方。