0
votes

In the cakephp blog tutorial in the Add Post add() action section

http://book.cakephp.org/2.0/en/tutorials-and-examples/blog/part-two.html

I can't understand what this $this->Post->create(); does, I tried to remove that line of code and it still works just fine. what does that line of code do?

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}   
1

1 Answers

0
votes

It creates a new instance of that model, which in turn creates a new record in your database table.

It is not necessary to call when adding data, but it is usually advised to because if you have referenced any other records previously, it will overwrite that data when you save. Calling create ensures you have a fresh slate to set data to.

Regular process of saving data:

  • create
  • set($your_data)
  • save