A
A
Allanian2016-08-08 10:31:22
MySQL
Allanian, 2016-08-08 10:31:22

How to write information to linked tables in Yii2?

I'm trying to write information to linked tables, tell me what's the problem?
There is an example of record in the connected tables, mb I not so declare it.
If you just display the form, fill it with data and display it on the page, everything is fine.
Gives an error message -

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yiiwork`.`work_news`, CONSTRAINT `category_id` FOREIGN KEY (`id_category`) REFERENCES `work_categorynews` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
The SQL being executed was: INSERT INTO `work_news` (`id`) VALUES (DEFAULT)

Those. is it not receiving data?
Controller function code
//Добавление новостей
    public function actionCreate()
    {
        $news = new News();
        $category = Categorynews::findOne(4);
        //загрузка и валидация
      if ($news->load(Yii::$app->request->post()) && $news->validate()) {
            //Блок загрузки изображения
          $file = UploadedFile::getInstance($news, 'image');   //Get the uploaded file
          $fp = fopen($file->tempName, 'r');
          //$content = fread($fp, filesize($file->tempName));
          $content = file_get_contents($file->tempName);
          fclose($fp);
          $news->image = $content;
        $category->link('news', $news);
        $news->save();
        return $this->render('entry-confirm', ['model' => $news]);
        } else {
            // либо страница отображается первый раз, либо есть ошибка в данных
            return $this->render('create', [
                'model' => $news,
            ]);
        }
    }

Код функции модели News
    public function getIdCategory()
    {
        return $this->hasOne(Categorynews::className(), ['id' => 'id_category']);
    }
Код функции модели Categorynews
    public function getNews()
    {
        return $this->hasMany(News::className(), ['id_category' => 'id']);
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2016-08-08
@webinar

The link method is designed for the hasOne connection The
question has already been understood here:
Yii2 many-to-many saving via link(), how to organize?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question