As for the storage verification of the data of model, I understand that if the front-end submits the data and needs the rule verification of model, if the back-end directly assigns the value and saves it, do you also need to do this to ensure the legitimacy of the data?
$transaction = Yii::$app->db->beginTransaction();
try {
$order = new Order();
$order->sn = ‘xxx’;
$order->product_id = 23;
if (!$order->save()) {
throw new Exception(‘订单创建失败:’ . json_encode($order->errors));
}
// 其他关联操作(如扣减库存)
$product = Product::findOne($order->product_id);
$product->stock -= $order->quantity;
if (!$product->save()) {
throw new Exception('库存扣减失败');
}
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
Yii::error($e->getMessage());
// 处理错误
}