belongsTo()不返回User的关系

时间:2016-06-19 20:34:58

标签: php laravel relationship has-and-belongs-to-many

我已经尝试了几件事,但我无法让它发挥作用。我希望能够制作类似{{ $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 }},但它不起作用,它返回错误 ErrorException:尝试获取非对象的属性(View:... / views /app/text.blade.php)。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

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

但是,根据您的可填写属性,您拥有的外键实际上是id_city

对于用户模型,

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

对于City模型,

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