我有一个 Laravel 模型,它有一个计算访问器:
模型作业有一些与用户相关联的作业应用程序。
我想知道用户是否已经申请了工作。
为此,我创建了一个访问器 user_applied
得到 applications
与当前用户的关系。这可以正常工作,但是每次访问该字段时都会计算访问器(进行查询)。
有没有什么简单的方法可以只计算访问器一次
/**
* Whether the user applied for this job or not.
*
* @return bool
*/
public function getUserAppliedAttribute()
{
if (!Auth::check()) {
return false;
}
return $this->applications()->where('user_id', Auth::user()->id)->exists();
}
提前致谢。
请您参考如下方法:
正如评论中所建议的,真的一点都不棘手
protected $userApplied=false;
/**
* Whether the user applied for this job or not.
*
* @return bool
*/
public function getUserAppliedAttribute()
{
if (!Auth::check()) {
return false;
}
if($this->userApplied){
return $this->userApplied;
}else{
$this->userApplied = $this->applications()->where('user_id', Auth::user()->id)->exists();
return $this->userApplied;
}
}