Answer the question
In order to leave comments, you need to log in
Yii. How it is better to make insert through one form at once in some tables in a DB?
Good day to all.
The situation is this.
There are 3 tables: product entities (id, name), product variants (id, product_id, size, color, count), images (id, product_id, image_full_path). This is an approximate list, there are a little more fields in each table, but I think this is enough for demonstration. The last 2 tables are connected with the first one by the "product_id" field and, accordingly, all the necessary relations are registered in the models. They are checked, when manually added to MySQL, the outputs (all kinds of views) work fine. Input problem =).
I do not ask you to write all the code completely and do everything for me. The principle or mb is important. a useful link or, if available, an example.
The question arose of how it is most correct from Yii to add all these fields at the same time in one click of the "save" button in one form, so as not to fence bicycles or crutches.
I myself seem to be inclined towards the method, upon successful addition of the product entity, to get its id and then parse the POST data of other groups of form fields (product options and product images). All in 1 action named "add". I don't know if this is correct or not. Help me to understand. Thanks in advance to everyone.
Answer the question
In order to leave comments, you need to log in
You can make a separate controller action with something like this:
<?php
$dbTransaction = $Yii::app()->db->getCurrentTransaction();
if (!$dbTransaction) {
$dbTransaction = Yii::app()->db->beginTransaction();
}
$productModel = new Product;
$productModel->attributes = $prodAttrs;
if (!$productModel->save()) {
$dbTransaction->rollback();
throw new CException("some");
}
foreach ($productModes as $productModeAttrs) {
$productModeModel = new productMode;
$productModeModel->attributes = $productModeAttrs;
$productModeModel->product_id = $productModel->id;
if (!$productModeModel->save()) {
$dbTransaction->rollback();
throw new CException("some");
}
}
// похожее с фото товаров
$dbTransaction->commit();
// redirect/render/return метода контроллера
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question