CakePHP save multiple rows

2019-05-21 18:23发布

I am using two models 'User' and 'UserImage'.. Where in i am going to save multiple rows into user_images table.. The view for UserImage is below..

echo $this->Form->input('UserImage.0.photo');
echo $this->Form->input('UserImage.1.photo');
echo $this->Form->input('user_id');
echo $this->Form->end(__('Submit'));

Then how to save multiple rows..

4条回答
爷、活的狠高调
2楼-- · 2019-05-21 18:24

From the doc of cakephp 2.x:

For saving multiple records of single model, $data needs to be a numerically indexed array of records like this:

    $data = array(
        array('title' => 'title 1'),
        array('title' => 'title 2'),
    );
$this->saveMany($data);

Note that we are passing numerical indexes instead of usual $data containing the Article key. When saving multiple records of same model the records arrays should be just numerically indexed without the model key.

It is also acceptable to have the data in the following format:

    $data = array(
        array('Article' => array('title' => 'title 1')),
        array('Article' => array('title' => 'title 2')),
    );
  $this->saveMany($data);

I have tried the first one and it worked great.

HTH.

查看更多
forever°为你锁心
3楼-- · 2019-05-21 18:24

you could use this one saveMany() to insert each image as new record. I used same to solve my problem. Every thing looks alright in paul.ago 's answer but just change saveAll() to saveMany()

$this->UserImage->saveMany($this->request->data);
查看更多
霸刀☆藐视天下
4楼-- · 2019-05-21 18:28

You should specify the model of each field if you have more models involved. Also, you need to specify for each record the related field (user_id).

Try this:

echo $this->Form->input('UserImage.0.user_id');
echo $this->Form->input('UserImage.1.user_id');

Plus use this to save multiple records and multiple models:

$this->UserImage->saveAll($this->request->data);
查看更多
SAY GOODBYE
5楼-- · 2019-05-21 18:47

See document of cakephp there is a method say saveAll() Cake PHP Saving Your Data

查看更多
登录 后发表回答