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