Laravel 5 现在有原子增量:
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 的旧答案,其中内置增量是单独的选择然后更新,这当然会导致多个用户出现错误:
如果您想通过确保更新是原子的来准确计算访问者,请尝试将其放入您的访问者模型中:
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 它应该是多余的。