P
P
phpForeve2017-02-26 03:24:01
MySQL
phpForeve, 2017-02-26 03:24:01

Yii2 2 records are saved to the database at once. Why?

The story is like this. When I go to the /create page, an entry is automatically created in the database. Then it redirects me to /update. Where do I start working with this record.

public function actionCreate(){
        $model = new NewsForm();
        $model->create_at = (new DateTime())->format('Y-m-d H:i:s');
        $model->update_at = (new DateTime())->format('Y-m-d H:i:s');
        if ($news = $model->create()) {
            //TODO Tosters
            //var_dump($news->id);
            return Yii::$app->getResponse()->redirect('/news/update/'. $news->id);
        }
    }

    public function actionUpdate()
    {
        $request = Yii::$app->request;
        $get = $request->get();

        $model = News::findOne($get['id']);

        if ($model->load(Yii::$app->request->post())) {
            $model->create_at = (new DateTime())->format('Y-m-d H:i:s');
            $model->update_at = (new DateTime())->format('Y-m-d H:i:s');
            if ($model->status != News::STATUS_ARCHIVE) {
                $model->publish_at = (new DateTime())->format('Y-m-d H:i:s');
            }
            if ($news = $model->create()) {
                //TODO Tosters
                Yii::$app->getResponse()->redirect('/news');
            }
        }

        return $this->render('update', compact('model'));
    }

If you do not redirect, then 1 record is created in the database. After the redirect, another one is created... Moreover, if you go to /update manually, no entries will be made. Is that how it is?
For example. /create creates $id = 105 (Tells me this). and $id = 106 comes to /update

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-02-26
@slo_nik

Goodnight.
Why is there no such check in the create action?
This
can be successfully replaced by
Why such a design?
Isn't it easier to write like this?

if ($model->save()) {
 // и получить id
  $model->id;

Where do you get $model->create() from and what's inside?
Here, Anton Natarov also suggested , why do you write this nonsense with time?
yii2 has a TimestampBehavior , use this class to set the time in the model, not in the controller.
Also check the status in the model, in the beforeSave() or AfterSave() methods

M
Maxim Timofeev, 2017-02-26
@webinar

The code is terrible, but it's most likely here:
You have it in both actions. Show the create method in the model.
By dates, I advise you to look at this:
demos.krajee.com/datecontrol - very convenient

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question