大卫 2018-01-08 14:55:14 217次浏览 1条评论 0 0 0

Yii2LockableQuery

MySQL InnoDB 引擎支持使用 select ... for update 来进行行锁。
这个插件增加了对ActiveQuery行锁的支持。

User::find()->where(['id'=>1])->forUpdate()->one();
表单验证
  • 评论于 2018-01-08 14:55 举报

    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

    <?php
    return [
        '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 = $model->getDb()->beginTransaction();
    try {
        $model = Sample::find()->where(['id'=>1])->forUpdate()->one();
        $dbTransaction->commit();
    } catch(\Exception $e) {
        $dbTransaction->rollBack();
        throw $e;
    }
    
    

    Licence

    MIT

    Links

您需要登录后才可以评论。登录 | 立即注册