update `test_ver` set `name`="lili" and `ver`=2 where `id`=1 and `ver`=1
/**
* 乐观锁
* @return string
*/
public function optimisticLock()
{
return 'ver';
}
public function updateRecord(){
$ver = self::findOne(['id'=>1]);
$ver->name = "lili";
$res = $ver->update();
return $res;
}
public function actionVersion(){
$testVer = new TestVer();
$res = $testVer->updateRecord();
return $this->render('version');
}
UPDATE `test_ver` SET `name`='lili', `ver`='2' WHERE (`id`='1') AND (`ver`='1')
protected function updateInternal($attributes = null)
{
if (!$this->beforeSave(false)) {
return false;
}
// 获取等下要更新的字段及新的字段值
$values = $this->getDirtyAttributes($attributes);
if (empty($values)) {
$this->afterSave(false, $values);
return 0;
}
// 把原来ActiveRecord的主键作为等下更新记录的条件,
// 也就是说,等下更新的,最多只有1个记录。
$condition = $this->getOldPrimaryKey(true);
// 获取版本号字段的字段名,比如 ver
$lock = $this->optimisticLock();
// 如果 optimisticLock() 返回的是 null,那么,不启用乐观锁。
if ($lock !== null) {
// 这里的 $this->$lock ,就是 $this->ver 的意思;
// 这里把 ver+1 作为要更新的字段之一。
$values[$lock] = $this->$lock + 1;
// 这里把旧的版本号作为更新的另一个条件
$condition[$lock] = $this->$lock;
}
$rows = $this->updateAll($values, $condition);
// 如果已经启用了乐观锁,但是却没有完成更新,或者更新的记录数为0;
// 那就说明是由于 ver 不匹配,记录被修改过了,于是抛出异常。
if ($lock !== null && !$rows) {
throw new StaleObjectException('The object being updated is outdated.');
}
$changedAttributes = [];
foreach ($values as $name => $value) {
$changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
$this->_oldAttributes[$name] = $value;
}
$this->afterSave(false, $changedAttributes);
return $rows;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有