Answer the question
In order to leave comments, you need to log in
Yii2. How to write a record to another table in a transaction?
Hello. I make record in db with svyazynnmi fields. But the transaction throws an error. It is necessary that $model->id be written to $address->user_id. In the base of the field tied.
if($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save()) {
Yii::$app->session->setFlash('success', 'Model save');
$address->save();
$transaction->commit();
Yii::$app->session->setFlash('success', 'User added');
return $this->refresh();
} else {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error');
}
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error2222');
}
}
Answer the question
In order to leave comments, you need to log in
Of course, I understand everything, but where is your connection. You fill in the data, but the connection itself is not created for you ... It does not appear from anywhere ...
Create a connection directly:
$customer = Customer::findOne(123);
$order = new Order();
$order->subtotal = 100;
// ...
// установка атрибута, которой задаёт связь "customer" в объекте Order
$order->customer_id = $customer->id;
$order->save();
if($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save()) {
$address->user_id = $model->id
Yii::$app->session->setFlash('success', 'Model save');
$address->save();
$transaction->commit();
Yii::$app->session->setFlash('success', 'User added');
return $this->refresh();
} else {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error');
}
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error2222');
}
}
$customer = Customer::findOne(123);
$order = new Order();
$order->subtotal = 100;
// ...
$order->link('customer', $customer);
if($model->load(Yii::$app->request->post()) && $address->load(Yii::$app->request->post())){
$transaction = Yii::$app->db->beginTransaction();
try {
if ($model->save()) {
$address->link('nameRelationModel', $model)
Yii::$app->session->setFlash('success', 'Model save');
$address->save();
$transaction->commit();
Yii::$app->session->setFlash('success', 'User added');
return $this->refresh();
} else {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error');
}
} catch (Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', 'Data error2222');
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question