分享一个乐观锁的代码,大家提点意见,优化优化
代码可以放在基类Model中
protected $cas_version = 'new_version';
public function cas() {
if(!$this->exists) {
return;
}
if(!in_array($this->cas_version, array_keys($this->original))) {
throw new \Exception('查询结果不包含version字段');
}
// 获取已经修改的字段
$dirty = $this->getDirty();
$query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey())->where($this->cas_version, $this->getOriginal($this->cas_version));
$dirty = array_merge($dirty, [$this->cas_version => $this->getOriginal($this->cas_version) + 1]);
$row = $query->update($dirty);
if ($row > 0) {
$this->syncChanges();
$this->syncOriginal();
}
return $row;
}