+1 vote
Good afternoon, ran into this problem:
There are two tables in the database, one for the details of the order, and another for the goods of this order.
I make an order, in the first table (for details of the order) recorded data, and the second table recorded only 1 line, instead of 2, 3, etc. (For example, if 3 types of goods should be recorded 3 lines of goods, but I have written only one line).
$order = new Orders();
$items = new OrdersItems();

//Сохранение заказа ...
// ................

//Сохранение товаров
if ($order->order_id){
foreach ($_SESSION['cart'] as $item){
$items->order_id = $order->order_id;
$items->product = $item['name'];
$items->product_id = $item['product_id'];
$items->price = $item['price'];
$items->qty = $item['qty'];
$session =Yii::$app->session;
return $this->redirect(['orders/view', 'id' => $order->order_id]);
RuslanTii By the way, I forgot to write.
There's package , it is convenient to use when saving linked data.
RuslanTii , please.
Only remove "crutches" from the code and you will be happy.
How to work correctly with YII you will find here .
Dmitry , Thank you very much, figured it out)
Good afternoon.
What a load of crap.
foreach ($_SESSION['cart'] as $item){
For session handling, yii2 has the necessary tools.
For each new entry, you need to create a new model instance. Approximately like this
foreach ($products as $product){
$model = new Product();
$model->order_id = $order->order_id;
$model->product = $product['name'];
$model->product_id = $product['product_id'];
$model->price = $product['price'];
$model->qty = $product['qty'];

1 Answer

0 votes
It is saved on the last cycle, it is easier to use the query $model->insert
Good morning.
The author of the question has a problem not with the method used, but with something else.