Laravel 5現擁有原子increment:
public function increment($column, $amount = 1, array $extra = [])
{
if (! is_numeric($amount)) {
throw new InvalidArgumentException('Non-numeric value passed to increment method.');
}
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
return $this->update($columns);
}
其基本上一樣:
Customer::query()
->where('id', $customer_id)
->update([
'loyalty_points' => DB::raw('loyalty_points + 1')
]);
下面是老回答Laravel 4,內置增量是單獨選擇,然後更新wh當然ICH導致與多個用戶的錯誤:
如果你想確保更新準確地計算你的訪問者是原子,然後嘗試把這個在您的訪客模式:
public function incrementTotalVisits(){
// increment regardless of the current value in this model.
$this->where('id', $this->id)->update(['totalVisits' => DB::raw('last_insert_id(totalVisits + 1)')]);
//update this model incase we would like to use it.
$this->totalVisits = DB::getPdo()->lastInsertId();
//remove from dirty list to prevent any saves overwriting the newer database value.
$this->syncOriginalAttribute('totalVisits');
//return it because why not
return $this->totalVisits;
}
我使用它適用於變更標籤系統,但也可能適合您的需求。
有沒有人知道要替換「$ this-> where('id',$ this-> id)」,因爲自從處理$ this Visitor之後,它應該是多餘的。
你的代碼在我的最後工作正常,還有什麼比你發佈的更多嗎? – ARW
增量方法被調用後,我應該調用save方法嗎? –
您不需要使用'increment'方法,因爲它確實打算用於以後不會保存的查詢。你也可以去$ visitor-> totalvisits = $ visitor-> totalvisits + 1; $ visitor->保存(); – ARW