[英]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);
并抛出以下内容:
“未定义的类常量'city'”
我该如何解决该问题?
表结构:
// users
+----+--------+---------+----------
| id | name | city_id | ...
+----+--------+---------+----------
| 1 | Jack | 5 | ...
// city
+----+--------+
| id | name |
+----+--------+
| 1 | Tehran |
您需要传递完整的类名:
return $this->belongsTo('App\City');
要么:
return $this->belongsTo(City::class);
另外,您不需要这样做:
$user_info = User::find(Auth::user()->id);
由于Auth::user()
已经加载了用户实例,因此您可以通过以下方式获取城市实例:
Auth::user()->city
基本上,您没有提供城市类别名称的完整路径,这就是您所属的To关系无法正常工作的原因。
例如您的代码必须是
return $this->belongs To('App/City');
因为您的应用程序文件夹中有城市类模块和其他模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.