简体   繁体   English

我如何在Laravel中建立一个EmiratesTo()关系?

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

Here is my model User.php 这是我的模型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');
    }
}

And here is a part of my controller: 这是我的控制器的一部分:

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

And it throws this: 并抛出以下内容:

"Undefined class constant 'city'" “未定义的类常量'city'”

How can I fix the problem? 我该如何解决该问题?


Tables structure: 表结构:

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

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

You need to pass full class name: 您需要传递完整的类名:

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

Or: 要么:

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

Also, you don't need to do that: 另外,您不需要这样做:

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

Because Auth::user() already has user instance loaded, you can just get city instance with: 由于Auth::user()已经加载了用户实例,因此您可以通过以下方式获取城市实例:

Auth::user()->city

Basically , you don't provide full path of your class name of city that's why you belongs To relation not working properly. 基本上,您没有提供城市类别名称的完整路径,这就是您所属的To关系无法正常工作的原因。

for example your code must be 例如您的代码必须是

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

Because your in app folder you have city class module and others. 因为您的应用程序文件夹中有城市类模块和其他模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM