Welcome Guest, Not a member yet? Register   Sign In
Stuck with CI4 Build Your First Application tutorial
#1

Hi everyone!

I’m a bit stuck with CI4 Build Your First Application tutorial.

Here https://codeigniter.com/user_guide/tutor...items.html in the News controller example we have method

$model->save([
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', true),
            'body'  => $this->request->getPost('body'),
        ]);

Scrolling down to “Model updating” there is no examples of insert() or update() functions. Is there something missing from the example, or do I just not understand how that should work.

I've used CI3 (intermediate skills) before but I'm new to CI4 (beginner).

Thank you in advance.

Gene
Reply
#2

Reread the first paragraph of the "Model Updating" section. When you call save(), if there's an id in the data array it will do an update, if not it will do an insert.
Quote:The only thing that remains is ensuring that your model is set up to allow data to be saved properly. The save() method that was used will determine whether the information should be inserted or if the row already exists and should be updated, based on the presence of a primary key. In this case, there is no id field passed to it, so it will insert a new row into it’s table, news.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

(This post was last modified: 11-11-2021, 10:13 AM by ikesela.)

They are in manual -> model.html#saving-data :
Code:
 
// Defined as a model property
$primaryKey = 'id';

// Does an insert()
$data = [
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', true),
            'body'  => $this->request->getPost('body'),
        ];

$model->save($data);

// Performs an update, since the primary key, 'id', is found.
 $data = [
             'id' => $this->request->getPost('post_id'),
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', true),
            'body'  => $this->request->getPost('body'),
        ];
$model->save($data);

Another Option:
Code:
$id_post = $this->request->getPost('post_id');
$data = [
            'title' => $this->request->getPost('title'),
            'slug'  => url_title($this->request->getPost('title'), '-', true),
            'body'  => $this->request->getPost('body'),
        ];
$model->insert($data);

$model->update($id_post,$data);

 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB