Cakephp:使用一个公共字段向单个Model添加多个记录

时间:2013-12-04 07:44:49

标签: php mysql cakephp cakephp-2.0 cakephp-2.3

我想在cakephp中为单个模型添加多条记录。我一直关注他的教程http://bit.ly/1jjR1U5,它就像魅力一样。但我需要从他的代码中进行微调。我需要在表单中创建一个对所有多个记录都通用的字段并保存模型。我在下面清楚地解释了他的代码和我需要的东西。

下面是他将多条记录添加到单个模型的代码。 在add.ctp中:

echo $this->Form->create('Model');
for($i = 0; $i < $count; $i++){
echo $this->Form->input("Model.$i.field1", array());
echo $this->Form->input("Model.$i.field2", array());
echo $this->Form->input("Model.$i.field3", array());
echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');

在Controller中,即在add()动作中的ModelController.php,

function add($count = 1){
if($this->request->is('post')){
    if($this->Model->saveAll($this->request->data['Model'])){
            $this->Session->setFlash(__('The Model has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The Model could not be saved. Please, try again.'));
        }
    $this->redirect(array('action' => 'index'));
}
    $this->set('count', $count);
}

上面的代码将在表中创建多个插入。我想要的是add.ctp表单,

echo $this->Form->create('Model');
echo $this->Form->input("field1", array());
for($i = 0; $i < $count; $i++){     
 echo $this->Form->input("Model.$i.field2", array());
 echo $this->Form->input("Model.$i.field3", array());
 echo $this->Form->input("Model.$i.field4", array());
}
echo $this->Form->end('add');

这里我希望Field 1对于要插入表中的记录是通用的。我不想循环它,因为客户端必须在每次迭代中为字段1选择相同的选项。 如果有人知道如何使用cakephp控制器或表单来实现这一点,请分享您的建议。

1 个答案:

答案 0 :(得分:3)

试试这个

$this->request->data = Hash::insert($this->request->data, 'Model.{n}.field1', $this->request->data['Model']['field1']);
$this->request->data = Hash::remove($this->request->data, 'Model.field1');
if($this->Model->saveAll($this->request->data['Model'])) {
    // your stuff goes here
}