Mirko Pagliai
Mirko Pagliai

Reputation: 1246

CakePHP 3.x: saving multiple records

I've read Converting Multiple Records. Now I'm trying to save multiple photos at once from a form.

With:

debug($this->request->data);

I've this:

[
    (int) 1 => [
        'filename' => '25483_106728809362869_5795827_n.jpg',
        'description' => '',
        'album_id' => '2'
    ],
    (int) 3 => [
        'filename' => '44569_193398817463220_816845208_n.jpg',
        'description' => '',
        'album_id' => '1'
    ]
]

It seems ok.

Bake has created for me this action method:

public function add() {
        $photo = $this->Photos->newEntity();

        if($this->request->is('post')) {
            $photo = $this->Photos->patchEntity($photo, $this->request->data);

            if($this->Photos->save($photo)) {
                return $this->redirect(['action' => 'index']);
            }
        }

        $this->set(compact('photo'));
    }

But the CakeBook doesn't explain well how to proceed. I sense I have to use newEntities() and patchEntities(), but I don't quite understand how to do.

For example: why the newEntity() method can accept NULL, while the method newEntities() necessarily wants an argument?? The save() method accepts only one entity at a time? So, I have to cycle saving for each entity?

Can I have a small example? Thanks.

Upvotes: 6

Views: 12901

Answers (2)

Manohar Khadka
Manohar Khadka

Reputation: 2195

Using saveMany:

In some occasions it would be even better using saveMany which don't need foreach loop anymore.

    $entities = $this->Photos->newEntities($this->request->data());
    if($this->Photos->saveMany($entities)) {
        // saved
    } else { 
        // error
    }

Upvotes: 2

Isaac Askew
Isaac Askew

Reputation: 1291

Assuming your data is in the correct format, it should be as simple as this:

$photos = $this->Photos->newEntities($this->request->data());

foreach ($photos as $photo) {
    $this->Photos->save($photo);
}

newEntity() can accept a null because calling newEntity with no data creates a blank entity that you can add data to, in case you don't want to pass in request data. For example:

$photo = $this->Photos->newEntity();
$photo->description = 'Cool!';
$photo->filename = 'example.jpg';

$this->Photos->save($photo);

newEntities(), however, expects multiple data or at least an array of data if you want to make many entities.

Upvotes: 8

Related Questions