第一种方法
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);
}
});
}