//创建事务 $tr = Yii::$app->db->beginTransaction(); try { for($i=1;$i<=3;$i++){ $test = new Areas(); $test->name = 'name'.$i; $test->sort=1; if($test->save()){ echo "save $i | "; } } $test = new Areas(); $test->name = 'ab'.$i; $test->sorta=1; //写入不存在的字段 if(!$test->save()){ "save fail"; //如果没有写入就输出 } //提交 $tr->commit(); } catch (Exception $e) { //回滚 $tr->rollBack(); echo "rollback"; }