L
L
littlefishily2020-02-24 17:52:31
Yii
littlefishily, 2020-02-24 17:52:31

How to write data to Yii2 intermediate table?

Hello! Unable to write data to intermediate table.
Database schema:
5e53da6cd45c8759159956.png

Added a checkboxlist to the form for adding an entry (area), which displays a list of workers from the workers table:

<?= $form->field($model, 'workAreas')->checkboxList(ArrayHelper::map(Workers::find()->all(), 'id', 'name')) ?>


In AreaController.php:
public function actionCreate()
    {
        $model = new Area();
        $workarea = new WorkArea();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            
            $workarea->area_id = $model->id;
            $workarea->worker_id = $model->workAreas;
            
          //$workarea->save();

            var_dump($workarea);

            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }


In the Area.php model:
public function getWorkAreas()
    {
        return $this->hasMany(WorkArea::className(), ['area_id' => 'id']);
    }


All the data is leaving the form and all of them are correct:
5e53deb9085bb567936479.png
var_dump($workarea) shows the required area_id, but the worker_id array is empty for some reason. I tried separately var_dump($model->workAreas), the array is also empty. If I substitute $workarea->worker_id = 7 (or any other) in the controller, then the entry in the database occurs correctly.

At this stage, I can’t understand why this is happening ( Please help me figure out why the data in the array is not visible. And also how to save the array correctly? So that the intermediate table looks like this:
5e53e2f167e13510052558.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2020-02-24
@littlefishily

Does the Area model have a property and rules for workAreas? How are they loaded from post into the model?
In the rules workAreas should be safe, then the array will be loaded and available. And yet, it must be translated into a string in order to save it to the database. worker_id must be of the appropriate type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question