徐善通的随笔

千里之行, 始于足下



Yii2.0中使用事务的方法


第一种方法

public function saveUserAvatar($userId, $params)
{
    $transaction = Yii::$app->db->beginTransaction();
        try {
            $user = User::findOne($userId);
            $user->scenario = 'set-avatar';
            $user->load($params);
            if (!$user->save()) {
                $errors = $user->getFirstErrors();
                $error = reset($errors);
                throw new DatabaseException(1, $error);
            }
            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage());
            Yii::error($e->getTraceAsString());
            throw $e;
        }
}

还有一种方法比较简洁,可以省去 try catch

public function saveUserAvatar($userId, $params)
{
    Yii::$app->db->transaction(function() use ($userId, $params) {
        $user = User::findOne($userId);
        $user->scenario = 'set-avatar';
        $user->load($params);
        if (!$user->save()) {
            $errors = $user->getFirstErrors();
            $error = reset($errors);
            throw new DatabaseException(1, $error);
        }
    });
}

作者: 徐善通
地址: https://www.xstnet.com/article-91.html
声明: 除非本文有注明出处,否则转载请注明本文地址


我有话说



最新回复


正在加载中....

Copyrights © 2016-2019 醉丶春风 , All rights reserved. 皖ICP备15015582号-1