A
A
AlexAll2018-10-10 11:07:09
MySQL
AlexAll, 2018-10-10 11:07:09

How to write data from one controller to different tables in yii2?

Hello, there are two tables
post[id, title, text]
site[id, title, link, post_id]
When creating a post, there are two fields for adding a site, with text and a link that are displayed using the https://github.com/ extension unclead/yii2-multiple-input
in the Post.php model I create a public $site variable and check that it is an array

[['site'], 'exist', 'allowArray' => true],

in vyshke _form I make a field
<?= $form->field($model, 'site')->widget(MultipleInput::className(), [
    
    'columns' => [
        [
            'name'  => 'title',
            'title' => 'Название сайта',
            'enableError' => true,
        ],
        
        [
            'name'  => 'link',
            'title' => 'Ссылка',
            'enableError' => true,
        ]
    ]
 ]);
?>

in controller
public function actionCreate()
    {
        $model = new Offers();
         if ($model->load(Yii::$app->request->post())) {
             if($model->save()) {
                foreach ($model->site as $var){
                $site = new Site();    
                $site->title = $var->title;
                $site->link = $var->link;
                $site>post_id = $model->id;
                $site->save();                
                
                }
               
             }
             
                    return $this->redirect(['view', 'id' => $model->id]);
                          
        }
        
        return $this->render('create', [
            'model' => $model,

        ]);
    }

I'm trying to write it gives an error at this place if($model->save()) {
Database Exception - yii\db\Exception
SQLSTATE[42000]: Syntax error or access violation: 1064 check the manual that corresponds to your MySQL server version for the right syntax to use near '[[]]) FROM `post` WHERE `post`.`site`=NULL' at line 1
The SQL being executed was: SELECT COUNT( DISTINCT [[]]) FROM `post` WHERE `post`.`site`=NULL
Error Info: Array
(
[0] => 42000
[1] => 1064
[2] => You have an error in your SQL syntax ; check the manual that corresponds to your MySQL server version for the right syntax to use near '[[]]) FROM `post` WHERE `post`.`site`=NULL' at line 1
)

What's wrong?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
C
chelkaz, 2018-10-10
@chelkaz

Try this: Instead of if($model->save())

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question