jos*_*c89 4 php optimization accessor laravel eloquent
我有一个 Laravel 模型,它有一个计算访问器:
模型Job有一些JobApplications与User相关联。我想知道用户是否已经申请了工作。
为此,我创建了一个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();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
正如评论中所建议的,真的一点都不棘手
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;
}
Run Code Online (Sandbox Code Playgroud)
}