【问题标题】:CakePHP: Overwrite existing duplicate dataCakePHP:覆盖现有的重复数据
【发布时间】:2012-04-24 23:48:12
【问题描述】:

如何让 Cake 使用 REPLACE INTO 而不是 INSERT INTO?我有一个将数据保存到数据库中的操作,但我不想有重复的条目。主键 (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 是因为我将数据保存到不同的模型。目前,此代码在尝试插入重复记录时出错,因为“字段”是唯一索引。在使用 CakePHP 之前,我只是使用了 REPLACE INTO 语法,没有任何问题。我想在 Cake 中实现类似的东西。

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

【问题讨论】:

    标签: cakephp duplicates overwrite


    【解决方案1】:

    指定数据中的主键:

    // 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
    

    【讨论】:

    • 值得注意的是还有其他方法可以做到这一点,例如在保存之前在模型上设置id参数。
    • 我不确定我是否清楚。我有大量未知大小的数据。我想循环数组并将每个条目保存为新记录,但避免插入重复项。
    • 同样的想法也适用。你怎么知道它是不是独一无二的?你有大数组中的id吗?如果是这样,请使用它。否则,您需要循环并通过其他一些独特的字段查找。您可能需要重新表述您的问题并包含可能的数组值的 sn-p。
    【解决方案2】:

    在 cakephp 3.0 中没有 $this->Model->create();它会返回未定义的错误。

    我们可以通过传递类似下面的数据来做到这一点

    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.'));
    	}
    }

    【讨论】:

      猜你喜欢
      • 2011-06-11
      • 2015-11-24
      • 1970-01-01
      • 2014-03-12
      • 2014-04-06
      • 2012-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多