企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
--- ### 1. 乐观锁 > class BaseModel extends Model { /** * 乐观锁更新 compare and update * @return bool|int * @throws Throwable */ public function cas() { throw_if(!$this->exists, \Exception::class,['model not exists when cas']); $dirty = $this->getDirty(); //修改之后的值 //是否有更新 if(empty($dirty)){ return 0; } //判断更新的值是否存在 $diff = array_diff(array_keys($dirty), array_keys($this->original)); throw_if(!empty($diff), \Exception::class, 'key ['.implode(',', $diff).'] not exists when cas!'); //拦截更新事件 if ($this->fireModelEvent('casing') === false) { return 0; } $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey()); //不带 delete or query foreach ($dirty as $key => $value) { $query = $query->where($key, $this->getOriginal($key)); } $row = $query->update($dirty); if ($row > 0) { $this->syncChanges(); //同步 changes $this->fireModelEvent('cased', false); $this->syncOriginal(); //同步数据库 } return $row; } /** * Register a casing model event with the dispatcher. * * @param Closure|string $callback * @return void */ public static function casing($callback) { static::registerModelEvent('casing', $callback); } /** * Register a cased model event with the dispatcher. * * @param Closure|string $callback * @return void */ public static function cased($callback) { static::registerModelEvent('cased', $callback); } }