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.
我有 然后 在我的 我一直收到错误 : p>
尝试获取非对象的属性 p>
blockquote>
不确定我做错了什么 这里。 外键关系都设置得很好。 我在 我们将不胜感激。 p>
div> Booking code>模型,可以有很多
Service code> 我已经在Booking模型中定义了这样的关系: p>
&lt;?php
namespace App;
use Illuminate \ Database \ Eloquent \ Model;
use App \ Service;
class Booking extends Model
{
/ **
*获取预订服务。
* / \ n公共功能服务()
{
返回$ this-&gt; hasMany('App \ Service');
}
}
code> pre>
BookingController code>中,我尝试获取当前预订的所有服务,如下所示: p>
public function create()
{
$ services = Booking :: find(1) - &gt; services;
返回视图('bookings.create');
}
code> pre>
services code>表中有一个
booking_id code>列,该列引用了
bookings code>表中的
id code>。 p> \ n
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 .