問題描述
我有這樣的數(shù)據(jù)庫表:
shoot: id, name, programme
programme: id, name
拍攝中的雄辯關(guān)系是這樣定義的:
The eloquent relationship in the shoot is defined like this:
public function programme() {
return $this->belongsTo('AppProgramme', 'programme', 'id');
}
使用 dd()
時,我可以看到這是正常工作的:
When using dd()
, I can see this is working correctly:
dd(Shoot:where('id','=',1)->with('programme')->first());
// prints the object with programme listed under the relationship
但是,當(dāng)我急切加載拍攝并嘗試獲取程序?qū)ο髸r,我反而檢索了拍攝屬性程序".例如:
However when I eager-load the shoot and attempt to get the programme object, I retrieve the shoot attribute "programme" instead. E.g.:
$shoot = Shoot:where('id','=',1)->with('programme')->first();
echo $shoot->programme; // returns 1, not AppProgramme object.
有沒有無需重寫大量代碼庫的解決方案?
Is there a solution to this without having to rewrite masses of the codebase?
推薦答案
relationship
和 column
名稱不應(yīng)使用相同的名稱,否則您將將始終收到 column
名稱,因此嘗試編輯其中之一,我認(rèn)為這里最簡單的是 relationship
名稱:
You shouldn't use the same name for the both relationship
and column
name, else you'll receive always the column
name so try to edit one of them, I think the easiest one here is the relationship
name :
public function programmeObj() {
return $this->belongsTo('AppProgramme', 'programme', 'id');
}
然后將其稱為:
echo $shoot->programmeObj;
注意:但如果你想遵循約定,你應(yīng)該用 programme_id
替換 name 屬性,所以:
NOTE : But if you want to follow conventions you should replace the name attribute by programme_id
so :
public function programme() {
return $this->belongsTo('AppProgramme', 'programme_id', 'id');
}
希望這會有所幫助.
這篇關(guān)于Laravel 獲取與其屬性同名的 Eloquent 關(guān)系的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!