Gyandeep Sharma
Gyandeep Sharma

Reputation: 2327

How to update multiple data in CakePHP

I need to save multiple rows with the different condition for each row.

Like :

Update orderdetails SET data = "'.$json1.'" WHERE order_id = 1;
Update orderdetails SET data = "'.$json2.'" WHERE order_id = 2;
Update orderdetails SET data = "'.$json3.'" WHERE order_id = 3;
Update orderdetails SET data = "'.$json4.'" WHERE order_id = 4;
Update orderdetails SET data = "'.$json5.'" WHERE order_id = 5;

I know the single row updation method of CakePHP, that I can run 5 times form to update all row.

But I want to save this by just only one line code that can run above query.

My Code

$update = array(
    array('data' => $json1,'order_id' => 1),
    array('data' => $json2,'order_id' => 2),
    array('data' => $json3,'order_id' => 3),
    array('data' => $json4,'order_id' => 4),
    array('data' => $json5,'order_id' => 5)
);
$this->Orderdetail->saveMany($update);

So, is there any way in CakePHP to achieve it...?

Upvotes: 0

Views: 426

Answers (1)

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2180

If I understand the above problem currently, you can achieve this by using the saveMany function in cakePHP. All you have to do is convert the data that you want to save in the form of an array and pass that single array to the saveMany function.

See here for more details

Here is a code sample for the above details in cakePHP 3:

$saveData = [
    [
        'order_id' => 1,
        'data' => $json1
    ],
    [
        'order_id' => 2,
        'data' => $json2
    ],
    [
        'order_id' => 3,
        'data' => $json3
    ],
    [
        'order_id' => 4,
        'data' => $json4
    ],
    [
        'order_id' => 5,
        'data' => $json5
    ]
];

$orderDetails = TableRegistry::get('Orderdetails');
$entities = $orderDetails->newEntities($saveData);
$result = $orderDetails->saveMany($entities);

For cakePHP 2.x:

See here for more details

Hope this is what you are looking for.

Edit: Based on the updated requirements, I guess the only way to achieve it is to make a custom query by using the Model->query method. You'll have to form a custom query for that which updates all the records in one go.

Upvotes: 2

Related Questions