2016-02-19 57 views
1

我有有一个计算访问一个Laravel模型:Laravel(雄辩)访问:只计算一次

型号工作有一些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(); 
} 

预先感谢任何容易方式。

回答

1

我,而不是创建一个你传递一个Job在您User模型的方法,并返回boolean是否应用的用户或不:

class User extends Authenticatable 
{ 
    public function jobApplications() 
    { 
     return $this->belongsToMany(JobApplication::class); 
    } 

    public function hasAppliedFor(Job $job) 
    { 
     return $this->jobApplications->contains('job_id', $job->getKey()); 
    } 
} 

用法:

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

干杯。这个很酷的转机肯定会解决这个问题。但是,如果有一种方法可以只计算一次访问器,那么它会很好... – josec89

+0

您可以在模型上设置一个属性。然后在随后的调用中,检查属性是否有值,如果是这样,则使用它,否则执行计算。 –

+2

是的,那会做诡计......相当棘手,但会起作用。谢谢! – josec89

1

正如评论中所建议的一样,真的没有棘手

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

}

0

可以user_applied值设置为model->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; 
} 

array_get将返回nullarray_set将评估值设置为'user_applied'密钥。在随后的调用中,array_get将返回之前设置的值。

这种方法的奖金优势是,如果你已经在你的代码(例如Auth::user()->user_applied = true)设置user_applied的地方,它会反映,这意味着它会返回一个值,而不做任何额外的东西。