[英]Laravel hasOne returns empty object
In my Laravel 8 application I two models, a User
and Optout
.在我的 Laravel 8 应用程序中,我有两个模型,一个
User
和Optout
。 My Optout
model has a user_id
column and a user is able to create an optout through a front-end form which populated this table with an entry with their user id.我的
Optout
模型有一个user_id
列,用户可以通过前端表单创建一个 optout,该表单使用带有用户 ID 的条目填充此表。
On my User
model when I try to create a relationship to get the optout I get an empty object instead of the data from my optout?在我的
User
模型上,当我尝试创建关系以获取选择退出时,我得到一个空对象而不是来自我的选择退出的数据? Why?为什么? What am I missing?
我错过了什么?
/**
* 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;
}
}
You don't need attributes for it.你不需要它的属性。 You need to create a relationship.
你需要建立关系。
public function output()
{
return $this->hasOne(Optout::class);
}
Then you can access it like $user->output
然后你可以像
$user->output
一样访问它
If you want only one field from that relation you can define attribute.如果您只想要该关系中的一个字段,您可以定义属性。
/**
* 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.