简体   繁体   中英

Cakephp saving multiple records at once

Is it possible to use save more then one record in cakephp using the $this->save(); function?

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 .

Example:

 $dataMulti = array(
        array(
            'Info' =>
            array(
                'note' => "This is note 1",
                'delete_flag' => "f"
            )
        ),
        array(
            'Info' =>
            array(
                'note' => "This is note 2",
                'delete_flag' => "f"
            )
        ),
        array(
            'Info' =>
            array(
                'note' => "This is note 3",
                'delete_flag' => "f"
            )
        ),
    );

Save many records in once time We have two way belows:

1. $infoModel->saveAll($dataMulti);

or

2. $infoModel->saveMany($dataMulti);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM