2017-04-12 70 views
0

我有一個Booking模型,它可以有很多Service's。Laravel一對多模型關係不起作用

我已經定義的預訂模型的關係是這樣的:

<?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表中,我有booking_id列,它在bookings表上引用id

任何幫助,將不勝感激。

+0

你已經導入了Booking類,你確定你的數據庫中有記錄 –

+1

'find'可以返回'null'。是否存在帶有id = 1的預訂? – lagbox

+0

@lagbox嗯,我認爲這是問題。沒有id = 1的預訂。我試着用預訂ID存在,它的工作。如果你寫這個作爲答案,我會高興地接受它。 – user3574492

回答

1

在這種特殊情況下的問題是,可能是雄辯無法找到id == 1預訂。

Booking::find(1);將在預訂主鍵上查詢1。如果沒有找到,它將返回null。試圖使用該null作爲對象是給「試圖獲取非對象的屬性」錯誤。

0

如果你的鑰匙是不是由laravel模型,你可以嘗試指定它們產生的:

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

看到你的上面的代碼:確保你有記錄ID爲1 ..如果是,請檢查你的主鍵和外鍵。