//定义事物 $transaction = Yii::$app->db->beginTransaction();
//try、catch块用来抓取错误,回退之前的DB操作 try { //$model为定义的需要保存对象
$model = new ExampleModel(); $model->name= 'Example'; //yii2的DB增删改操作发生异常时,不会抛出异常,所以,需要添加throw抛出异常 if (!$model->save()) { throw new Exception(); } //提交事物 $transaction->commit(); } catch (Exception $e) { //出错时,回滚 $transaction->rollBack(); }