Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between save and saveAll function in cakephp?

Tags:

cakephp

can any one give example please


2 Answers

save is used to simply save a model:

Array
(
    [ModelName] => Array
    (
        [fieldname1] => 'value'
        [fieldname2] => 'value'
    )
)

Assuming the above information was stored in an array called $data, one would call

$this->ModelName->save($data);

in order to INSERT a record into the model's table (if id field is not specified) or UPDATE a record of the model's table (if id field is specified).

saveAll is used to:

Save multiple records of a model

Array
(
    [Article] => Array
    (
        [0] => Array
        (
            [title] => title 1
        )
    [1] => Array
        (
            [title] => title 2
        )
    )
)

So, you may save many models at the same time instead of looping and using save() each time.

Save related records of a model

Array
(
    [User] => Array
    (
        [username] => billy
    )
    [Profile] => Array
    (
        [sex] => Male
        [occupation] => Programmer
    )
)

This would save both User and Profile models at the same time. Otherwise, you would have to call save() for User first, obtain the id of the newly saved user and then save Profile with user_id set to the obtained id.

Examples taken straight from the book.

like image 161
RabidFire Avatar answered Jul 02 '26 09:07

RabidFire


saveAll saves all model data in a form, whereas save only saves one. So you would use save to save a single value, while saveAll basically saves you the trouble of using a loop for save.

like image 40
Kyle Avatar answered Jul 02 '26 07:07

Kyle