我有问题,因为只有循环中的最后一项保存在数据库中。 我正在使用 CakePhp 2.x
Controller :
for ($x=1; $x <= count($this->request->data['Goodsandoffer'])/3;$x++){
$promID = $this->request->data['Goodsandoffer']['promotionaloffer_id_'.$x];
if($this->request->data['Goodsandoffer']['cenaPromocyjna_'.$x] != ''){
$helperReqestTable3 = array('promotionaloffer_id'=>$this->request->data['Goodsandoffer']['promotionaloffer_id_'.$x],'good_id'=>$this->request->data['Goodsandoffer']['good_id_'.$x],'cenaPromocyjna'=>$this->request->data['Goodsandoffer']['cenaPromocyjna_'.$x]);
$helperReqestTable['Goodsandoffer']=$helperReqestTable3;
debug($helperReqestTable);
$this->Goodsandoffer->save($helperReqestTable);
}
}
这是我在循环中调试的样子:
array(
'Goodsandoffer' => array(
'promotionaloffer_id' => '7',
'good_id' => '18',
'cenaPromocyjna' => '1'
)
)
在接下来的交互中:
array(
'Goodsandoffer' => array(
'promotionaloffer_id' => '7',
'good_id' => '19',
'cenaPromocyjna' => '2'
)
)
在数据库中只创建一行最后一项。
型号:
class Goodsandoffer extends AppModel {
public $displayField = 'id';
public $belongsTo = array(
'Promotionaloffer' => array(
'className' => 'Promotionaloffer',
'foreignKey' => 'promotionaloffer_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Good' => array(
'className' => 'Good',
'foreignKey' => 'good_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
}
最佳答案
您是否尝试过在调用保存之前调用 $this->Goodsandoffer->create()
?这样一来,您肯定每次都告诉 Cake 创建新记录。
Cake中创建和保存数据的一般流程是:
$this->Model->create()
$this->Model->set($data_array)
$this->Model->save()
您还可以通过将 $data_array
传递给 save()
函数来消除上面的第 2 步:
$this->Model->create();
$this->Model->save($data_array);
注意: from the manual (如果您没有使用 create()
):
When calling save in a loop, don’t forget to call clear().
您可以创建新数据的另一种方法是确保您的模型的主键在您传递给保存的数据集中为 null
,尽管这不太明显并且可能最好坚持创建/[设置/]保存流程:
$data = array('id' => null, 'somefield' => 'foobar');
$this->Model->save($data); // new record created
关于php - 为什么只有最后一项保存在数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25274118/