How to update multiple rows in cakephp

2.1k Views Asked by At

I have a table called lists. This list is filled with multiple rows at a time. The first time the table is filled with 3 rows. And after that, any update of this table may be 2 rows or 6 rows.

I want to delete/update accordingly. Meaning, if the next update has less rows than the current, then the rest of the rows should be deleted. Or if the next row is greater then the current row, then the respective rows should update and the rest are added with auto incremented id's.

I am using CakePHP 2.6.7.

1

There are 1 best solutions below

0
On

I'm not sure if I understood your question, but maybe you want to use something like Model::saveAll()

$data = array(
    array('id' => 1, 'body' => 'Comment 1'),
    array('id' => 2, 'body' => 'Comment 2')
);
$this->Comment->saveAll($data);

That will execute the following commands:

UPDATE `blog`.`comments` SET `id` = 1, `body` = 'Comment 1' WHERE `blog`.`comments`.`id` = 1

UPDATE `blog`.`comments` SET `id` = 2, `body` = 'Comment 2' WHERE `blog`.`comments`.`id` = 2

To delete more than one record use Model::delete():

$this->Comment->delete(array(1, 2), false);

That will execute the following SQL command:

DELETE `Comment` FROM `blog`.`comments` AS `Comment` WHERE `Comment`.`id` IN (1, 2)`

Read more about Model::updateAll() and Model::saveAll() here, and about Model::delete() and Model::deleteAll() here

I hope it will help you.