使用单个模型插入多个记录

时间:2013-04-15 10:52:27

标签: cakephp-2.0

我想插入多个记录。这是我的ci = ontroller代码:

if(empty($this->data) == false)
            {
                for($i=0;$i<=count($this->data['Breakdown']);$i++)
                {
                    echo count($this->data['Breakdown']);
                    $this->Breakdown->create(); 
                    if($this->Breakdown->save($this->data)) 
                    {

                         $this->Session->setFlash('Quantity Breakdown has been added Successfully.', 'default', array('class' => 'oMsg1 oMsgError1'));
                         //$this->redirect('qty_breakdown');
                    } 
                }

            }
            else
             {
              $this->set('errors', $this->Breakdown->invalidFields());   
             }

我的问题是,如果我只在文本字段中放入一个值,它会插入八次记录。我想要一个解决方案,使用此代码完美地插入它吗?

1 个答案:

答案 0 :(得分:1)

通过Model :: saveMany()

保存多个记录

您不必手动循环数据,CakePHP模型能够自动处理所有这些,只要您根据CakePHP约定创建表单

通过FormHelper

创建正确的表单输入

为了使其正常工作,您发布的数据应符合CakePHP惯例;

例如:像这样创建表单输入:

echo $this->Form->input('Breakdown.1.field1');
echo $this->Form->input('Breakdown.1.field2');

// ....

echo $this->Form->input('Breakdown.99.field1');
echo $this->Form->input('Breakdown.99.field2');

在调试控制器内的发布数据时,应该如下所示:

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

array(
    'Breakdown' => array(
        (int) 1 => array(
            'field1' => 'value of field1 in row 1',
            'field2' => 'value of field2 in row 1'
        ),
        (int) 2 => array(
            'field1' => 'value of field1 in row 2',
            'field2' => 'value of field2 in row 2'
        )
    )
)

保存数据 - 控制器代码

然后,在你的控制器内:

public function qty_breakdown()
{
    $this->layout = 'common';

    if ($this->request->is('post') && !empty($this->data['Breakdown'])) {
        if ($this->Breakdown->saveMany($this->data['Breakdown'])) {
            $this->Session->setFlash(
                'Quantity Breakdown has been added Successfully.',
                'default',
                array('class' => 'oMsg1 oMsgError1')
            );
            $this->redirect('qty_breakdown');
        } else {
            // NOTE: If you're using the FormHelper, you DON'T
            // have to do this, the FormHelper will automatically
            // mark invalid fields 'invalid'
            $this->set('errors', $this->Breakdown->invalidFields());

            // However, it's Good practice to set a general error message
            $this->Session->setFlash('Unable to save your data');
        }
    }
}

文档

本文档的这一部分描述了Model::saveMany()