2015-11-24 47 views
1

在1個工作時,我一直在Laravel 5收到此錯誤:1的數據庫關係:1:Laravel 1間的關係返回未定義的屬性

Undefined property: Illuminate\Database\Eloquent\Collection::$owner 

在我的控制,我有方法的「東西」。當我返回$東西我得到:

[{"id":4,"demoId":2,"slug":"loremipsum","languageId":1,"countryId":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}] 

關係是「demoId」。

在我的模型,我有這樣的:

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

我使用這個代碼,這給出了一個錯誤:

$routine = $stuff->owner->get()->toArray(); 

我希望得到的demotable2的信息。我做錯了什麼?

+0

爲@smartrahat說,你應該把'owner'方法在模型中,而不是在你的控制器 – tacone

回答

1

有跡象表明,你需要申請當您嘗試讓最有說服力(convention over configuration)的某些規則,你的問題是,在命名你foreign key的,當你使用:

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

雄辯希望找到的demoId一個foreign keydemo_id相反,當你改變外鍵的名稱,你需要像這樣的關係來指定它:

public function owner(){ 
    return $this->belongsTo('App\Demotable2', 'demoId', 'id'); 
} 

你更多的在這裏讀到:http://laravel.com/docs/5.1/eloquent-relationships

+1

特別提幫助轉換/配置部分。我確實改變了所有的表格名稱。它現在有效。 – user5512902

+0

是的,這是一個很好的做法,慣例優於配置,代碼編寫和更多的權力 – teeyo

1

我認爲這段代碼將在你的模型中。

public function owner(){ 
    return $this->belongsTo('App\Demotable2'); 
} 
0

的關係在模型中定義的,而不是控制器。

App\Stuff.php

public function owner() { 
    return $this->belongsTo(App\Demotable2::class); 
} 

當運行這個關係,它會自動尋找一個owner_idstuff表。但是,您正在使用demoId。對於工作,你有你的關係來定義外鍵

public function owner() { 
    return $this->belongsTo(App\Demotable2::class, 'demoId'); 
} 
+0

謝謝你的答案,因爲你的答案是我必須選擇teeyo相同,theyo添加一個資源的鏈接,並提到約定配置部分。 Tha是我接受他的答案的原因,但你的確也在幫助。 – user5512902