龙空技术网

Yii2支持MySQL行锁

IT生涯 157

前言:

如今小伙伴们对“yiimysql”可能比较讲究,兄弟们都需要学习一些“yiimysql”的相关资讯。那么小编也在网上收集了一些对于“yiimysql””的相关文章,希望咱们能喜欢,看官们一起来了解一下吧!

Yii2 的 ActiveQuery 默认不支持 MySQL 的行锁。于是扩展了一下。 欢迎来搞。

Yii2 Lockable ActiveQuery

This package allows you to use pessimistic locking (select for update) when you work with ActiveRecord Query.

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist amoydavid/yii2lockable-query "*"

or add

"amoydavid/yii2lockable-query": "*"

to the require section of your composer.json.

Usage

Set schema map for database connection

<?phpreturn [ 'class' => 'yii\db\Connection', 'schemaMap' => [ 'mysql' => '\amoydavid\Yii2LockableQuery\mysql\Schema', // set up mysql schema ], 'dsn' => 'mysql:host=localhost;dbname=yii', 'username' => 'root', 'password' => '', 'charset' => 'utf8', // Schema cache options (for production environment) //'enableSchemaCache' => true, //'schemaCacheDuration' => 60, //'schemaCache' => 'cache',]; 

Extend your ActiveRecord class via \amoydavid\Yii2LockableQuery\ActiveRecord

/**

* Class Sample

* @package common\models

*

*/

class Sample extends \amoydavid\Yii2LockableQuery\ActiveRecord { ... }

Use model locks in transaction.

$dbTransaction = Yii::$app->db->beginTransaction();try { $model = Sample::find()->where(['id'=>1])->forUpdate()->one(); $dbTransaction->commit();} catch(\Exception $e) { $dbTransaction->rollBack(); throw $e;}

标签: #yiimysql