开发者

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

can any 开发者_JAVA技巧one give example please


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.


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.


As of Cake 2.0

save Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.

saveAll Saves multiple individual records for a single model; Also works with a single record, as well as all its associated records.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜