2016-02-19 104 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的地方,它會反映,這意味着它會返回一個值,而不做任何額外的東西。