I have a News model and a Files model. News has the connection 'files'=>array(self::HAS_ONE, 'Files', 'news_id') . I need to get one news, do the things I need with it and add the file to the linked table files. I try to do this:

 $model=News::model()->findByPk($_GET['id']); $model->files = new Files; $model->files->name = "Имя файла"; $model->save() 

It is possible to edit the received news, but the record in the files table is not added. Tell me what I'm doing wrong?

    1 answer 1

    If you want to save this way, then afterSave of the main model is apparently not redefined by you to save the connected model, example yiiframework.ru/doc/cookbook/ru/model.save.related.data

    • From this recipe it is not clear how to make by analogy - Jeque
    • Just in the News model, override the afterSave method by analogy with an example, only you will have one entry instead of an array: $ this-> files-> news_id = $ this-> id; $ this-> files-> save (); - Reinq
    • Redefined. If you display the object $ this-> files, then you can see that values ​​are assigned to attributes: ["_attributes":"CActiveRecord":private]=> array(2) { ["name"]=> int(11111) ["news_id"]=> int(23) } , but save () still does not save to the database - Jeque
    • See what it outputs when saving if it is added to afterSave () var_dump($this->files->save()); var_dump($this->files->getErrors()); var_dump($this->files->save()); var_dump($this->files->getErrors()); - Reinq
    • Nothing deduces anything - Jeque