S
S
Sergey2016-02-23 22:17:56
Yii
Sergey, 2016-02-23 22:17:56

Why is it stored like this in the database?

there is a Product table with one of the columns tied, it is assumed that related products will be entered there, so its filling is set in the form

<?php 
        $product=Product::find()->where('category_id='.$cat->id)->all();
                foreach($product as $prod){ ?>
                    <?= $form->field($model, 'tied['.$prod->title.']')->checkbox(['value' => $prod->title, 'label' => $prod->title])
                    }
            ?>

here is the part of the action that is responsible for saving to the database
if ($model->load(Yii::$app->request->post())) {
                $post=Yii::$app->request->post();
                foreach($post ["Product"]["tied"] as $tied){
                    $model->tied .=$tied."%";
                }
                $model->save();
           }

But for some reason, the values ​​​​are not overwritten in the database and are added. Do not tell me why and how to deal with it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Natarov, 2016-02-24
@HanDroid

I understand that you have one class used i.e. just a product?
If so, then mass work and updates are carried out like this.
In controller:

public function actionUpdate()
    {
        // Тут получаете свой cat либо передаете каким либо образом. 
        $products = Product::find()->where('category_id'= $cat->id)->indexBy('id')->all();

        if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {
            foreach ($products as $product) {
                $product->save(false);
            }
            return $this->redirect('index');
        }
        return $this->render('update', ['products' => $products]);
    }

As
$form = ActiveForm::begin();

foreach ($products as $index => $product) {
    echo $form->field($product, "[$index]value")->checkbox(['value' => $prod->title, 'label' => $prod->title]);
}

ActiveForm::end();

If you are using more than one model and related things i.e. like User and Profile, then you need to work with multiple models
. Also, if you are working with relationships, you can use eager loading. loading and linking this way
//получаете продукты и связи за один запрос.
$products = Product::find()->with('category', 'someTied')->all();

//или с условием
$products = Product::find()->with([
    'categpry' => function ($query) {
        $query->andWhere(['category_id' => 15]);
    },
])->all();

If you need to save or update the connected Ids of different objects, there is a link method.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question