【问题标题】:How can I do a belongsTo() relation in Laravel?如何在 Laravel 中建立 belongsTo() 关系?
【发布时间】:2017-12-11 08:08:43
【问题描述】:

这是我的模型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 |

【问题讨论】:

    标签: php mysql laravel eloquent relational-database


    【解决方案1】:

    你需要传递完整的类名:

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

    或者:

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

    另外,您不需要这样做:

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

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

    Auth::user()->city
    

    【讨论】:

    • WTF ...!我从来不明白 laravel 在后台到底做了什么。
    • 一个问题,列名不规范怎么办?例如,如果我用city_idd 替换列的名称city_id $this->belongsTo(City::class); 应该是什么样子?
    • @stack 如果列名是city_idd,则将关系改为$this->belongsTo(City::class, 'city_idd');
    【解决方案2】:

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

    例如你的代码必须是

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2019-05-26
      • 2021-02-06
      • 2015-01-20
      • 1970-01-01
      相关资源
      最近更新 更多