CakePHP save multiple rows

橙三吉。 提交于 2019-12-10 10:33:10

问题


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


回答1:


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);



回答2:


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




回答3:


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.




回答4:


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);


来源:https://stackoverflow.com/questions/10396708/cakephp-save-multiple-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!