donglan9651
2017-06-13 16:35
浏览 215
已采纳

Laravel 5 - 没有为belongsTo显示任何关系

Its been a while since I have worked on a Laravel project and cannot see why this issue is happening.

I have a 'vehicles' table and also a 'customers' table.

In the vehicles table there is a row with a fields 'customer_id' that has the value of 1. There is a also a customer in 'customers' table with the id of 1.

In my Vehicle model I have:

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

But when returning the data from the query:

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

The relations array is blank.

Where my mistake on this one? No errors, just no data.

图片转代码服务由CSDN问答提供 功能建议

自从我参与Laravel项目以来,已经有一段时间了,并且无法理解为什么会出现这个问题。

我有一个'车辆'表和一个'客户'表。

在车辆表中有一行带有'customer_id'字段 值为1.在'customers'表中还有一个id为1的客户。

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

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

但是 从查询返回数据时:

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

relations数组是空白的。

我的错误在哪一个? 没有错误,只有没有数据。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyi4912 2017-06-13 16:38
    已采纳

    If you want to get a customer with the vehicle:

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

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dounue6984 2017-06-13 18:15

    Wouldn't it be better if you define you relations like, assuming this is a One-To-Many Relationship?

    In the Vehicles Model:

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

    In the Customers Model

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

    Then load whatever you need

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

    But the relationship will be loaded only when called:

    $vehicle->customer;
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题