Есть таблица с товарами и таблица с категориями, которые связаны промежуточной таблицей, так как один и тот же товар может быть в нескольких категориях.
При сохранении или изменении товара связь с категориями обрабатывается в afterSave():
Код: Выделить всё
if($this->categories && !empty($this->categories)){
$this->unlinkAll('cats', true);
foreach($this->categories as $value){
$item = PartsCategories::findOne($value);
$this->link('cats', $item);
}
}
Пытаюсь загрузить экселевскую таблицу с товарами в другом контроллере:
Код: Выделить всё
if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file');
if ($model->upload()) {
$data = \moonland\phpexcel\Excel::import('uploads/' . $model->file->name, [
'setFirstRecordAsKeys' => false,
'setIndexSheetByName' => false
]);
foreach($data as $key => $value){
$id = $value['B'];
$item = Parts::findOne($id);
if(!$item){
$item = new Parts();
}
$categories = explode(', ', $value['I']);
$item->categories = $categories;
$item->save();
}
Yii::$app->session->setFlash('success', "Импорт выполнен");
return $this->redirect(Yii::$app->request->referrer);
}
}
Call to a member function getIsNewRecord() on null
if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
}