insertOnDuplicate并不适用于Magento

时间:2014-06-03 15:17:10

标签: php mysql magento

所以我试图检查自定义数据库表,如果'某些事情'列在' test_type'列中,用新数据替换现有行。但是,它仍在继续编写重复列值' test_type'在数据库表中。所以我最终得到了两排“'在' test_type'列。

            $adapter = Mage::getSingleton('core/resource')->getConnection('core_write');
            $data = array(
                'test_type' => 'something',
                'time_stamp' => $timeStamp,
            );
            $adapter->insertOnDuplicate('test_table', $data, array('test_type'));

以下是创建表格的更新脚本。

<?php

$installer = $this;
$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS {$installer->getTable('test_table')};
CREATE TABLE `{$installer->getTable('test_table')}` (
  `auto_id` int(10) NOT NULL auto_increment,
  `test_type` varchar(50) NOT NULL,
  `time_stamp` varchar(50) NOT NULL,
  PRIMARY KEY  (`auto_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");
$installer->endSetup();

1 个答案:

答案 0 :(得分:7)

为了使数据库理解重复行意味着test_type与现有行相同的行,您可以将test_type添加为唯一索引中的列,例如< / p>

UNIQUE KEY `test_type_idx` (`test_type`)

因此将表创建代码更改为;

<?php

$installer = $this;
$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS {$installer->getTable('test_table')};
CREATE TABLE `{$installer->getTable('test_table')}` (
  `auto_id` int(10) NOT NULL auto_increment,
  `test_type` varchar(50) NOT NULL,
  `time_stamp` varchar(50) NOT NULL,
  PRIMARY KEY  (`auto_id`)
  UNIQUE KEY `test_type_idx` (`test_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

");
$installer->endSetup();

修改

另一个问题是将第三个参数传递给insertOnDuplicate方法。如果存在重复,则应指定需要更新的字段,因此可能time_stamp

$adapter->insertOnDuplicate('test_table', $data, array('time_stamp'));