A
A
AlexAll2019-03-05 14:12:00
Yii
AlexAll, 2019-03-05 14:12:00

Why in yii2 in the controller in the field where the id is written through a loop, the save model gives an error that this is an array?

Here is such a control, for some reason this line $item->order_id = $model->id; gives an error when saving that this is an array, although if you wardump $item->order_id or $model->id it gives the usual int number
Here is the controller

public function actionOrder() {

        $model = new Order();
        $item = new OrderItem();
        $cart = $this->service->getCart();
        if ($model->load(Yii::$app->request->post())) {
            $model->status = 'on';
            if ($model->save()) {
                $items = $this->cart->getItems();
                foreach ($items as $product) {
                    $item->order_id = $model->id;
                    $item->item_id = $product->getProductId();
                    $item->quantity = $product->getQuantity();
                    $item->item_price = $product->getCost();
                      if(!$item->save()){
                        var_dump($item->errors);
                        die;
                    }
                }

            }
        }
        return $this->redirect(['index']);
    }

What's wrong? I broke my whole head, in other controllers I used this method, while saving pictures in a separate database and everything is ok

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-03-05
@slo_nik

Good afternoon.
Maybe that would be better?

foreach ($items as $product) {
                    $item = new OrderItem();
                    $item->order_id = $model->id;
                    $item->item_id = $product->getProductId();
                    $item->quantity = $product->getQuantity();
                    $item->item_price = $product->getCost();
                      if(!$item->save()){
                        var_dump($item->errors);
                        die;
                    }
                }

And it would not hurt to show the full text of the error.

M
Maxim Timofeev, 2019-03-05
@webinar

To begin with, instead of

foreach ($items as $product) {
                    $item->order_id = $model->id;

do
foreach ($items as $product) {
                    $item = new OrderItem();
                    $item->order_id = $model->id;

since you are overwriting the same model, well, give the code of the OrderItem model itself and what var_dump produces

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question