Laravel 一对多模型关系无效

Laravel one to many model relationship not working

我有一个 Booking 模型,它可以有很多 Service 个。

我在 Booking 模型中定义了这样的关系:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Service;

class Booking extends Model
{

    /**
     * Get the services for the booking.
     */
    public function services()
    {
        return $this->hasMany('App\Service');
    }
}

然后在我的 BookingController 中,我尝试像这样获取当前预订的所有服务:

    public function create()
    {       
        $services = Booking::find(1)->services;
        return view('bookings.create');
    }

我一直收到错误消息:

Trying to get property of non-object

不确定我做错了什么。外键关系都设置好了。我在 services table 中有一个 booking_id 列,它引用 bookings table.

上的 id

如有任何帮助,我们将不胜感激。

如果您的密钥不是由 laravel 模型生成的密钥,您可以尝试指定它们:

return $this->hasMany('App\Service', 'foreign_key', 'local_key');

在这种特殊情况下,问题可能是 Eloquent 找不到 id == 1 的预订。

Booking::find(1); 将查询 1 预订的主键。如果找不到,它将 return null。尝试将 null 用作对象会出现 "Trying to get property of non-object" 错误。

public function create()
    {       
        $services = Booking::find(1)->services;
        return view('bookings.create');
    }

通过查看上面的代码:确保您有 ID 为 1 的记录。如果是,请检查您的主键和外键。