提问者:小点点

CakePHP:覆盖现有的重复数据


我怎样才能让蛋糕使用替换而不是插入?我有一个将数据保存到数据库的操作,但我不希望有重复的条目。主键(id)是唯一的,如果该值已经存在,我不希望它作为新行输入。

正在保存的数据也是动态生成的,因此退出时出现错误是不合适的。

初始编辑我保存的数据位于单个大数组中

$data = Array([0] => 'value1', [1] => 'value2', [2] => 'value3') etc

我试图循环遍历这个数组,将每个值保存为一个新记录

foreach ($data as $value) { 
    $save_data['Model'] = array('field' => $value);
}
Classregistry::init('Model')->saveAll($save_data);

我使用Classregistry是因为我正在将数据保存到另一个模型。当前,在尝试插入重复记录时,此代码会失效,因为“field”是唯一的索引。在使用CakePHP之前,我只是在语法中使用了REPLACE,没有任何问题。我想在蛋糕上做点类似的事情。

目前我唯一的解决方法是允许输入重复项,但仅通过分组来显示唯一的行。


共2个答案

匿名用户

指定数据中的主键:

// create a new record
$this->Model->create();
$this->Model->save(array(
  'Model' => array(
    'name' => 'new record'
  )
));

// update it
$this->Model->save(array(
  'Model' => array(
    'id' => $id,
    'name' => 'updated record'
  )
));

在“编辑”视图中,只需输入:

echo $this->Form->input('id'); // or your custom PK field

匿名用户

在cakephp 3.0中没有$this-

我们可以通过像下面这样传递数据来做到这一点

foreach($sizeCategories as $sizeData){
	
	$iteamData['Item_Code']		= 'abc-'.$sizeData->sizes_id;
	$iteamData['Item_Desc']		= '';
	$iteamData['Article_ID']	= 0;
	$iteamData['ColorId']		= $colorData;
	$iteamData['CreatedBy'] 	= $this->request->session()->read('Auth.User.id');
	$iteamData['CreatedDate'] 	= Time::now();
	$iteamData['UpdateDate']  	= Time::now();
	$iteamData['Status']  		= '1';
	
	// Generaly we used $this->ItemMaster->patchEntity($itemMaster, $iteamData); that will update the data and overwrite the same entry again & again we should use the $this->ItemMaster->newEntity($iteamData);	
	// save data in loop 
	$itemMaster = $itemMaster = $this->ItemMaster->newEntity($iteamData);			
	
	if ($this->ItemMaster->save($itemMaster)) {
		$this->Flash->success(__('The products has been generated.'));
	}else{
		$this->Flash->error(__('The products could not be generate. Please, try again.'));
	}
}