belongsTo() 不返回用户的关系

belongsTo() not returning relationships for User

我已经尝试了几件事,但我无法让它工作。我希望能够做出这样的东西 {{ $user->city->name }}

我的用户模型:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public $timestamps = false;
    protected $table = 'users';
    protected $fillable = ['id_city', 'name', 'email', 'password', 'admin'];
    protected $hidden = ['password', 'remember_token'];

    public function city()
    {
        return $this->belongsTo('App\City');
    }
}

这是我的城市模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    public $timestamps = false;
    protected $table = 'cities';
    protected $fillable = ['name', 'slug'];

    public function users(){
        return $this->hasMany('App\User');
    }
}

我正在尝试在我的视图中使用 {{ $user->city->name }},但它不起作用,它 returns 一个错误 ErrorException: 尝试获取 属性非对象(视图:.../views/app/text.blade.php).

我该怎么办?

在您的 belongsTo 关系中,Eloquent 默认情况下尝试将 city_id 匹配为外键,因为您没有传递第二个参数。

但是根据你的fillable属性,你的外键其实是id_city.

对于用户模型,

public function city()
{
    return $this->belongsTo('App\City', 'id_city');
}

对于城市模型,

public function users(){
    return $this->hasMany('App\User', 'id_city', 'id');
}