【问题标题】:Laravel 5 - No relations showing for belongsToLaravel 5 - 没有显示为 belongsTo 的关系
【发布时间】:2017-06-14 02:15:36
【问题描述】:

我从事 Laravel 项目已经有一段时间了,不明白为什么会出现这个问题。

我有一个“车辆”表和一个“客户”表。

在车辆表中,有一行字段“customer_id”的值为 1。“customers”表中还有一个 ID 为 1 的客户。

在我的车辆模型中,我有:

public function customer()
{
    return $this->belongsTo('App\Customer');
}

但是当从查询返回数据时:

$vehicle = Vehicle::find($id);
dd($vehicle);

关系数组为空。

我的这个错误在哪里?没有错误,只是没有数据。

【问题讨论】:

  • 您没有加载(也没有急切或懒惰)关系

标签: php laravel laravel-5 eloquent


【解决方案1】:

如果您想用车辆吸引客户:

$vehicle = Vehicle::with('customer')->find($id);

https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

【讨论】:

    【解决方案2】:

    如果你定义你的关系会不会更好,假设这是一个一对多的关系?

    在车辆模型中:

    public function customer()
    {
        return $this->belongsTo('App\Customer', 'id', 'customer_id');
    }
    

    在客户模型中

    public function vehicle()
    {
        return $this->hasOne('App\Vehicle', 'customer_id', 'id');
    }
    

    然后加载你需要的任何东西

    $vehicle = Vehicle::find($id); 
    

    但关系只有在调用时才会加载:

    $vehicle->customer;
    

    【讨论】:

    • 不错的建议,但在这种情况下,一辆车只能属于一个客户,但一个客户可以拥有许多不同的车辆(如果他们购买不止一辆)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2018-08-05
    • 2021-04-05
    • 1970-01-01
    • 2018-03-08
    • 2020-01-15
    • 2019-06-27
    相关资源
    最近更新 更多