我有一个Laravel模型,其中有一个计算的访问器:
模型Job有一些与User相关联的JobApplications。 我想知道用户是否已经申请了这个工作。
为此,我创建了一个名为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();
}
提前感谢。