在我的 Laravel 8 應用程式中,我有兩個模型,aUser和Optout. 我的Optout模型有一個user_id列,用戶可以通過前端表單創建一個選擇退出,該表單使用帶有用戶 ID 的條目填充此表。
在我的User模型上,當我嘗試創建關系以獲取選擇退出時,我得到一個空物件而不是來自我的選擇退出的資料?為什么?我錯過了什么?
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'has_marketing_optout'
];
/**
* Determine if the user is currently subscribed or not
*
* @return bool
*/
public function getHasMarketingOptoutAttribute()
{
try {
return $this->hasOne(Optout::class, 'user_id');
} catch (\Exception $e) {
return false;
}
}
uj5u.com熱心網友回復:
你不需要它的屬性。你需要建立關系。
public function output()
{
return $this->hasOne(Optout::class);
}
然后你可以像訪問它$user->output
如果您只想要該關系中的一個欄位,您可以定義屬性。
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'has_marketing_optout'
];
public function output()
{
return $this->hasOne(Optout::class);
}
public function getHasMarketingOptoutAttribute()
{
return $this->output->field_name;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485942.html
上一篇:DB::get是Laravel中的陣列,但它說它不是陣列
下一篇:在Laravel中生成URL
