I want to save 10 times in Cakephp using Save function with for loop but it doesn't seem to work. It only saves one data.
How can we make it so it saves multiple data at one call?
Below is my code...
for($i=0;$i<10;$i++){
$unique_id = $this->_unique($userData['User']['id']); // Unique id with userid as initial prefix
$this->data['Invite'] = array('invited_user' => $userData['User']['id'], 'unique_id' => $unique_id);
$this->User->Invit开发者_如何学编程e->save($this->data['Invite']);
}
You need to call Model::create( ) for each iteration of the loop. IE:
<?php
for( $i=0; $i<10; $i++ ){
$this->User->Invite->create( );
$unique_id = $this->_unique($userData['User']['id']);
$this->data['Invite'] = array('invited_user' => $userData['User']['id'], 'unique_id' => $unique_id);
$this->User->Invite->save($this->data['Invite']);
unset( $this->data[ 'Invite' ] );
}
?>
The answer is in the following book, page 94: Source: Bari, Ahsanul. CakePHP Application Development (p. 94). Packt Publishing. Kindle Edition. This is the what you can find in the book, and the answer to this question:
$this->Book->create();
$this->Book->save($this->data);
Note: It is important to call the model's create() method just ahead of calling the model's save() method if the intention is to create a new record.
In other words, you need to use create() before save() every time you use save().
精彩评论