Laravel一对多的模特关系不起作用

I have a Booking model which can have many Service's.

I have defined the relationship in the Booking model like this:

<?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');
    }
}

Then in my BookingController I try to get all the services for the current booking like this:

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

I keep getting the error:

Trying to get property of non-object

Not sure what I'm doing wrong here. The foreign key relation is all set up fine. I have a booking_id column in the services table which references id on the bookings table.

Any help would be appreciated.

In this particular case the issue is probably that Eloquent can't find a Booking with id == 1.

Booking::find(1); is going to query on the primary key for Booking for 1. If it is not found it will return null. Trying to use that null as an object is giving the "Trying to get property of non-object" error.

If your keys are not the ones generated by the laravel models you can try to specify them:

return $this->hasMany('App\Service', 'foreign_key', 'local_key');
public function create()
    {       
        $services = Booking::find(1)->services;
        return view('bookings.create');
    }

By seeing your above code: Ensure that you have record with id 1..if it is , check your primary and foreign key .