I am writing a parser that receives information from the site. It turns out such an array:

$array( [category]=>'Loren ipsum' [description]=>'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.' [name]=>'За словесными горами' [desc]=>'Далеко-далеко за словесными горами в стране гласных и согласных живут рыбные тексты. Вдали от всех живут они в буквенных домах на берегу Семантика большого языкового океана.' [cat]=>'Lorem ipsum' ); 

There are category and post models of the following content:

 category ->id,name, description; post ->id,name,description,id_category 

Accordingly, in the controller, I will write to the database as follows:

 $category= new Category(); $post =new Post(); if ($model->load(Yii::$app->request->post()) ) { $category->name = $array['category']; $category->description=$array['description']; $category->save(); $post->name=$array['name']; $post->description=$array['desc']; } 

How can I find out the id $category just created here in order to be written in the id_category post?

  • $category->save(); $inserted_id = $category->id_category; will help? - Alexey Shimansky
  • @ Alexey Shimansky, that is, you mean $ category-> save (); $ post = $ category-> id? - Sergalas
  • Well, you specified id_category so I wrote this way ... I do not know where you have any fields ... and $post you have a model, so, rather $post->чего-то там = $category->id; .... apparently $post->id_category = $category->id; - Alexey Shimansky
  • @ Alexey Shimansky yes now you have written like mine. And the fact that the category has just been created, and $ category-> id is AUTO_INCREMENT is nothing? - Sergalas
  • Nothing ...... generally the standard create function looks like if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } ....... as we see if something is saved in the database - redirect to the page with the newly created data .... autoincrement is the most it) - Alexey Shimansky

0