如何在 Laravel 中建立 belongsTo() 关系?

How can I do a belongsTo() relation in Laravel?

这是我的模型User.php

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'cell_phone', 'province_id', 'city_id', 'job'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

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

这是我的控制器的一部分:

$user_info = User::find(Auth::user()->id);
dd($user_info->city);

它抛出这个:

"Undefined class constant 'city'"

我该如何解决这个问题?


表结构:

// users
+----+--------+---------+----------
| id |  name  | city_id | ...
+----+--------+---------+----------
| 1  | Jack   | 5       | ...

// city
+----+--------+
| id |  name  |
+----+--------+
| 1  | Tehran |

您需要传递完整的 class 姓名:

return $this->belongsTo('App\City');

或:

return $this->belongsTo(City::class);

此外,您不需要这样做:

$user_info = User::find(Auth::user()->id);

因为Auth::user()已经加载了用户实例,您可以通过以下方式获取城市实例:

Auth::user()->city

基本上,您没有提供 class 城市名称的完整路径,这就是您属于关系无法正常工作的原因。

例如您的代码必须是

return $this->belongs To('App/City');

因为您的应用程序文件夹中有城市 class 模块和其他模块。