[英]Overriding a Laravel Eloquent Model in an accessor returns 0 on using a property
對(也許)有點不清楚的疑問表示抱歉。 我不知道該如何用其他任何方式。 (建議:p)但是代碼本身說明了我的想法:
我正在使用訪問器來獲取頁面的主題(如果沒有主題,則從頁面的父項獲取):
public function getThemeAttribute()
{
if(!isset($this->theme_uid) || $this->theme_uid === null || $this->theme_uid === '')
{
return $this->parent->theme()->first();
}
//return $this->theme->first();
return self::theme()->first();
}
如果我請求主題屬性本身,這確實可行,例如:
$page->theme
哪個返回:
Theme {#741 ▼ ...etcetera
但是,如果我嘗試訪問返回的模型上的屬性,例如:
$page->theme->uid
我得到:
0
可能與引擎蓋下發生的事情有關,但尚未弄清楚,因此任何幫助都將是很大的。
已經謝謝你了!
問候吉斯
好的,作為一個小的代碼改進:
(!isset($this->theme_uid) || $this->theme_uid === null) === !isset($this->theme_uid)
isset —確定是否設置了變量並且不為NULL
現在這部分:
return $this->theme->first();
將導致魔術方法__get
遞歸並引發異常。 https://bugs.php.net/bug.php?id=71254
在您的情況下, theme
是關系,而不是屬性。 我認為attribute
訪問器應用於其預期目的- attribute
訪問突變。 您可以通過自定義關系表達您的情況:
public function availableTheme()
{
if(!empty($this->theme_uid))
{
return $this->theme();
}
return $this->parent->theme();
}
// $page->availableTheme
// $page->avalaibleTheme()->where(...)->first()
好的,所以我使用的方法如下:
public function getThemeAttribute()
{
if(!isset($this->theme_uid) || $this->theme_uid === null || $this->theme_uid === '')
{
return (object)$this->parent->theme()->first()->getAttributes();
}
return (object)self::theme()->first()->getAttributes();
}
這使我可以使用一種不錯的語法來訪問值(例如: $page->theme->uid
或$page->theme->color
而不必擔心它是在父級上還是哪種類型上) ( Relation
, Model
等)主題的返回值為。
如果有人可以告訴我為什么不能直接做到這一點,我仍然非常感興趣,任何在這里提供幫助的人:謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.