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

前端 未结 3 1667
慢半拍i
慢半拍i 2021-01-21 21:41

can any one give example please

相关标签:
3条回答
  • 2021-01-21 22:12

    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.

    0 讨论(0)
  • 2021-01-21 22:16

    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 讨论(0)
  • 2021-01-21 22:30

    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.

    0 讨论(0)
提交回复
热议问题