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

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

4

1 回答 1

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

于 2013-04-15T19:54:33.763 回答