Php Laravel(雄辩)访问者:仅计算一次

Php Laravel(雄辩)访问者:仅计算一次,php,laravel,optimization,eloquent,accessor,Php,Laravel,Optimization,Eloquent,Accessor,我有一个Laravel模型,它有一个经过计算的访问器: 模型作业具有一些与用户关联的作业应用程序。 我想知道用户是否已经申请了工作 为此,我创建了一个访问器user\u applicated,它获取与当前用户的应用程序关系。这可以正常工作,但每次我访问字段时都会计算访问器(进行查询) 有没有简单的方法只计算一次访问者 /** * Whether the user applied for this job or not. * * @return bool */ public functio

我有一个Laravel模型,它有一个经过计算的访问器:

模型作业具有一些与用户关联的作业应用程序。 我想知道用户是否已经申请了工作

为此,我创建了一个访问器
user\u applicated
,它获取与当前用户的
应用程序
关系。这可以正常工作,但每次我访问字段时都会计算访问器(进行查询)

有没有简单的方法只计算一次访问者

/**
 * 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();
}

提前感谢。

我会在您的
用户
模型上创建一个方法,您可以将
作业
传递给该方法,并返回一个布尔值,以确定用户是否已应用:

类用户扩展可验证性
{
公共职能职位申请
{
返回$this->belongtomany(JobApplication::class);
}
公共函数已应用于(作业$Job)
{
返回$this->jobApplications->contains('job_id',$job->getKey());
}
}
用法:

$applied=User::hasAppliedFor($job);

正如一篇评论中所建议的那样,一点也不棘手

 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;
    } 

}

您可以将
user\u applied
值设置为
model->attributes
数组,并在下次访问时从attributes数组返回该值

public function getUserAppliedAttribute()
{
    $user_applied =  array_get($this->attributes, 'user_applied') ?: !Auth::check() && $this->applications()->where('user_id', Auth::user()->id)->exists();
    array_set($this->attributes, 'user_applied', $user_applied);
    return $user_applied;
}
第一次访问
数组时,它将返回
null
,这将导致执行
?:
的下一面。
array\u set
将评估值设置为
'user\u applicated'
键。在随后的调用中,
array\u get
将返回以前设置的值


这种方法的额外优势是,如果您在代码中的某个地方设置了
user\u applicated
(例如
Auth::user()->user\u applicated=true
),它将反映出这一点,这意味着它将返回该值,而不做任何额外的操作

干杯。这种冷静的转变肯定会解决这个问题。但是如果有一种方法可以只计算一次访问器,那就太好了……您可以在模型上设置一个属性。然后在随后的调用中,检查属性是否有值,如果有,则使用该值,如果没有,则执行计算。是的,这样做就可以了。。。相当棘手,但会起作用。谢谢没问题。很高兴能帮忙!