1

I am using cakephp 2.5 and I have an array that I wish to update many records at once in the Page model. I can't seem to get the format of the array correct. I get the error:

Notice (8): Undefined index: newOrder [APP/Controller/PagesController.php, line 133]

$newOrder = array(
        'Page' => array(
            0 => array(
                'id' => 3,
                'order' => 0),
            1 => array(
                'id' => 4,
                'order' => 0),
            2 => array(
                'id' => 7,
                'order' => 0
            )
));
$this->Page->updateAll($newOrder);

One of the parts I think I am missing is using 'data' as part of the array. But I am unsure where to place it.

I have also tried:

$this->Page->updateAll($newOrder['Page']);

1 Answer 1

7

You should use saveMany for your requirement. Find the explanation below -

updateAll

updateAll(array $fields, array $conditions) - is used to update one or more records with the same value based on a condition or multiple conditions. eg: If you want to update all your pages & set all of them to order = 0, you can use updateAll without passing the primary keys -

$this->Page->updateAll(
    array('Page.order' => 0)
);

If you want to update some pages based on a condition you will do something like -

$this->Page->updateAll(
    array('Page.order' => 0),
    array('Page.type' => 'PROMOTED')
);

Assuming you have a type field in your page model, the above query will set order 0 for all pages with type PROMOTED

Ref - http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions

saveMany

Now if you want to update some specific records with some specific values which you want to create in an array, you should use a saveMany(array $data = null, array $options = array())

To save/update multiple records using a data array, you should first create the data array in this format -

$data = array(
 array('Page' => array('id' => 1, 'order' => 0)),
 array('Page' => array('id' => 2, 'order' => 0)),
 array('Page' => array('id' => 3, 'order' => 0))
);
$this->Page->saveMany($data);

Now you can use saveMany to update the three records with the given id(primary key) with order 0. Note if you don't pass primary keys i.e id in the arrays, saveMany will just create new records for the given array.

Ref - http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.