Не происходит удаления в таблице?

Всем привет, в админке есть инпут поле от картика Select2, там я выбираю вкус и добавляю их в таблицу сохранения и обновления (когда добавляю новый вкус) все сохраняется.
1464197f0e.png

А а когда все убираю то получаю такую ошибку, если по одному удалять то все отлично работает!
f45a961ed2.png

Как реализовать правильное удаления одного или всех пункта вкусов

Есть три таблицы:
taste: тут хранятся все вкусы
id, title

has_product_taste: это связанные таблица с taste и product_pit
id, product_pit, taste_id

связи настроены
Модель ProductPit
public function getHasProductTaste()
    {
        return $this->hasMany(HasProductTaste::className(), ['product_id' => 'id']);
    }

    public function getTastes()
    {
        return $this->hasMany(Taste::className(), ['id' => 'taste_id'])->via('hasProductTaste');
    }

    public function afterFind()
    {
        $this->taste_array = $this->tastes;
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        $arr = ArrayHelper::map($this->taste_array, 'id', 'id');
        foreach ($this->taste_array as $one) {
            if (!in_array($one, $arr)) {
                $model = ($model = HasProductTaste::find()
                    ->where(['product_id' => $this->id])
                    ->andWhere(['taste_id' => $one])
                    ->one()) ? $model : new HasProductTaste();

                $model->product_id = $this->id;
                $model->taste_id = $one;
                $model->save();
            }
            if (isset($arr[$one])) {
                unset($arr[$one]);
            }
        }
        HasProductTaste::deleteAll(['taste_id' => $arr, 'product_id' => $this->id]);
    }


В модели HasProductTaste также есть связь с моделью taste
public function getTaste()
    {
        return $this->hasOne(Taste::className(), ['id' => 'taste_id']);
    }


view
<?= $form->field($model, 'taste_array')->widget(Select2::classname(), [
            'data' => ArrayHelper::map(Taste::find()->all(), 'id', 'title'),
            'language' => 'ru',
            'options' => ['placeholder' => 'Выбрать вкусы ...', 'multiple' => true],
            'pluginOptions' => [
                'allowClear' => true,
                'tags' => true,
                'maximumInputLength' => 10
            ],
        ])->label('Вкусы');
        ?>
  • Вопрос задан
  • 117 просмотров
Пригласить эксперта
Ответы на вопрос 1
Uman
@Uman Автор вопроса
PHP, YII2
Все решил, надо было сделать проверку
if ($this->taste_array) {
            foreach ($this->taste_array as $one) {
                if (!in_array($one, $arr)) {
                    $model = ($model = HasProductTaste::find()
                        ->where(['product_id' => $this->id])
                        ->andWhere(['taste_id' => $one])
                        ->one()) ? $model : new HasProductTaste();

                    $model->product_id = $this->id;
                    $model->taste_id = $one;
                    $model->save();
                }
                if (isset($arr[$one])) {
                    unset($arr[$one]);
                }
            }
        }
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы