Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 550
Mirko Pagliai Avatar asked May 04 '15 22:05

Mirko Pagliai


1 Answers

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.

like image 136
Isaac Askew Avatar answered Sep 20 '22 16:09

Isaac Askew