amoydavid / yii2lockable-query
ActiveRecord 的 MySQL InnoDB 锁支持(select for update)
v1.1.1
2019-12-06 08:45 UTC
Requires
- php: ~7.0
- yiisoft/yii2: ~2.0
This package is auto-updated.
Last update: 2024-09-06 19:33:41 UTC
README
此软件包允许你在操作 ActiveRecord 查询时使用悲观锁(select for update)。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令:
php composer.phar require --prefer-dist amoydavid/yii2lockable-query "*"
或者将以下内容添加到你的 composer.json 的 require 部分:
"amoydavid/yii2lockable-query": "*"
to the require section of your composer.json.
用法
为数据库连接设置模式映射
<?php
return [
'class' => 'yii\db\Connection',
'schemaMap' => [
'mysql' => '\amoydavid\Yii2LockableQuery\mysql\Schema', // set up mysql schema
'mssql' => '\amoydavid\Yii2LockableQuery\mssql\Schema', // set up mssql schema
],
'dsn' => 'mysql:host=localhost;dbname=yii',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
// Schema cache options (for production environment)
//'enableSchemaCache' => true,
//'schemaCacheDuration' => 60,
//'schemaCache' => 'cache',
];
通过 \amoydavid\Yii2LockableQuery\ActiveRecord 扩展你的 ActiveRecord 类
/**
* Class Sample
* @package common\models
*
*/
class Sample extends \amoydavid\Yii2LockableQuery\ActiveRecord { ... }
在事务中使用模型锁
$dbTransaction = $model->getDb()->beginTransaction();
try {
$model = Sample::find()->where(['id'=>1])->forUpdate()->one();
$dbTransaction->commit();
} catch(\Exception $e) {
$dbTransaction->rollBack();
throw $e;
}
许可证
MIT