CakePHP 3.x: saving multiple entries

I read Convert multiple records . Now I am trying to save several photos from the form at once.

WITH

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

I have it:

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

Seems good.

Bake created this action method for me:

 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 CakeBook does not explain how to proceed. I feel like I need to use newEntities() and patchEntities() , but I don't quite understand how to do this.

For example: why can the newEntity() method accept NULL, and newEntities() method necessarily want an argument? Does the save() method accept only one entity at a time? So, do I need to save the save cyclically for each object?

Can I take a small example? Thanks.

+6
source share
2 answers

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

 $photos = $this->Photos->newEntities($this->request->data()); foreach ($photos as $photo) { $this->Photos->save($photo); } 

newEntity() can be null because calling newEntity without data creates an empty object to which you can add data in case you do not want to pass request data. For instance:

 $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 objects.

+8
source

Using saveMany:

In some cases, it would be even better to use saveMany, which no longer needs a foreach loop.

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

Source: https://habr.com/ru/post/986533/


All Articles