php - Magento Zend_Db_Adapter_Abstract::更新问题

标签 php mysql magento zend-db magento-1.5

我编写了一个模块,可以接收 CSV 文件并将数据添加到 sales_flat_order 表(代码如下)。尽管我对通过 Magento 与数据库进行交互指导持怀疑态度并且缺乏知识,但我还是能够成功地更新表中的必要列。但是,每次我运行代码时,它都会更新行,但总是会向表中添加一个额外的行,其中包含所有空值。我已经尝试打印出原始 SQL,但我没有看到任何无关的 SQL 调用,但它一直在这样做。

以下是重要的代码片段,应该有助于解释我在做什么。希望这是其他人遇到的已知问题,并能为我指明正确的方向。

首先,这是我的 config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
    <modules>
        <VPS_Sorting>
            <version>0.1.0</version>
        </VPS_Sorting>
    </modules>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <sorting after="Mage_Adminhtml">VPS_Sorting</sorting>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <global>
        <models>
            <sorting>
                <class>VPS_Sorting_Model</class>
                <resourceModel>sorting_mysql4</resourceModel>
            </sorting>
            <sorting_mysql4>
                <class>VPS_Sorting_Model_Mysql4</class>
<!--                 Doesn't need entities when you aren't using your own table!! -->
            </sorting_mysql4>
        </models>
        <blocks>
            <sorting>
                <class>VPS_Sorting_Block</class>
            </sorting>
        </blocks>

        <resources>
            <!-- this section used to install/configure the DB dynamically -->
            <sorting_setup>
                <setup>
                    <module>VPS_Sorting</module>
                    <class>VPS_Sorting_Model_Mysql4_Setup</class>
                </setup>
                <connection>
                    <use>core_setup</use>
                </connection>
            </sorting_setup>
            <!-- end setup section -->

            <sorting_write>
                <connection>
                    <use>core_write</use>
                </connection>
            </sorting_write>
            <sorting_read>
                <connection>
                    <use>core_read</use>
                </connection>
            </sorting_read>
        </resources>
    </global>
    <adminhtml>
        <acl>
            ...
        </acl>
    </adminhtml>
</config>

正如评论中所说,我没有提供任何实体,因为我没有使用自己的表(它使用销售/订单资源模型进行初始化(见下文)

接下来,我将其添加到我的 system.xml 文件中,以将文件导入框添加到配置中:

<importcsv translate="label">
    <label>Import CSV</label>
    <comment>
        <![CDATA[requires 2 columns, 'order_id' and 'real_ship_cost']]>
    </comment>
    <frontend_type>import</frontend_type>
    <backend_model>sorting/import_csv</backend_model>
    <sort_order>5</sort_order>
    <show_in_default>1</show_in_default>
    <show_in_website>1</show_in_website>
    <show_in_store>1</show_in_store>
</importcsv>

这是在 system.xml 中用于上传框的 backend_model 类:

class VPS_Sorting_Model_Import_Csv extends Mage_Core_Model_Config_Data
{
    protected function _construct()
    {
        parent::_construct();
        $this->_init('sorting/csv'); //initialize the resource model
    }


    public function _afterSave()
    {
        if($rm = $this->_getResource())
            $rm->uploadAndImport($this);

        else
            Mage::logException("Failed to load VPS_Sorting Resource Model");
    }
}

最后,这一切的核心是完成所有工作的模型资源类。您可以在这里看到,我在构造函数中调用了 _init('sales/order'),这样我就可以利用 sales_order 资源模型,而不必建立单独的数据库连接(我假设这个没关系......它正在工作,但如果这是个坏主意,请告诉我)

class VPS_Sorting_Model_Mysql4_Csv extends Mage_Core_Model_Mysql4_Abstract
{
    protected $_adapter;

    protected function _construct()
    {
        $this->_init('sales/order', 'entity_id');
    }

    public function uploadAndImport(Varien_Object $object)
    {
        $csvFile = $_FILES['groups']['tmp_name']['actions']['fields']['importcsv']['value'];
        $io = new Varien_Io_File();
        $info = pathinfo($csvFile);
        $io->open(array('path' => $info['dirname']));
        $io->streamOpen($info['basename'], 'r');

        // check and skip headers
        $headers = $io->streamReadCsv();

        //        return parent::_afterSave();
        if ($headers === false || count($headers) < 2 || $headers[0] != 'order_id' || $headers[1] != 'real_ship_cost')
        {
            $io->streamClose();
            Mage::throwException("Invalid Real Shipping Cost CSV Format.  File must contain 2 columns: 'order_id' and 'real_ship_cost'");
        }

        //Varien_Db_Adapter_Pdo_Mysql
        $this->_adapter = $this->_getWriteAdapter();

        $this->_adapter->beginTransaction();

        try {
            $importData = array();

            while (false !== ($csvLine = $io->streamReadCsv()))
            {
                if (empty($csvLine)) {
                    continue;
                }

                $importData[] = array('id' => $csvLine[0], 'rsc' => $csvLine[1]);

                if (count($importData) == 5000) {
                    $this->_saveImportData($importData);
                    $importData = array();
                }
            }

            $this->_saveImportData($importData);

            $io->streamClose();
        } catch (Mage_Core_Exception $e) {
            $this->_adapter->rollback();
            $io->streamClose();
            Mage::throwException($e->getMessage());
        } catch (Exception $e) {
            $this->_adapter->rollback();
            $io->streamClose();
            Mage::logException($e);
            Mage::throwException('An error occurred while importing Real Shipping Cost data.');
        }

        $this->_adapter->commit();

        return $this;
    }


    protected function _saveImportData($_data)
    {
        foreach($_data as $_row)
        {
            $this->_adapter->update($this->getMainTable(), array('real_ship_cost' => $_row['rsc']), array('`increment_id` = ?' => $_row['id']));
        }
    }
}

我删除了很多调试语句以简化它,但重要的是要注意,如果我回显 $importData 数组的大小,它始终是我的 CSV 预期的 3。如果我将日志记录添加到 Zend_Db_Adapter_Abstract 以打印它运行的每个 SQL 语句,它只运行 3。所以我不知道为什么要插入额外的行。

在此先感谢您的帮助!

最佳答案

我不是 100% 确定发生这种情况的原因,但我找到了解决方案。我认为这是由以下事实引起的:默认情况下,任何 Mage_Core_Model_Config_Data 对象都将其值存储在 core_config_data 表中。由于我将其初始化为使用我自己的资源模型,该模型实际上搭载在 sales/order 资源模型上,因此它感到困惑并试图将虚假信息保存到 sales/order 表中.

为了修复它,我做了以下事情:

首先,在 system.xml 中使用的 backend_model 类的构造函数中,将 _dataSaveAllowed 标志设置为 false :

protected function _construct()
{
    parent::_construct();
    $this->_init('sorting/csv'); //initialize the resource model
    $this->_dataSaveAllowed = false;
}

接下来,不要使用 _afterSave 来处理 CSV 导入,而是使用 _beforeSave(当您不允许时,不会调用 _afterSave保存数据)

这似乎已经解决了我的问题,但如果我的方法有缺陷,我欢迎提出任何意见/建议。我在这方面还是新手,所以任何有经验的见解总是值得赞赏的:)

关于php - Magento Zend_Db_Adapter_Abstract::更新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7197352/

相关文章:

magento - 除默认值外,未保存在商店中的可配置产品的产品名称

Magento - 非卖品

magento - Google Plus 分享按钮显示错误图像

php - 使用php在不同的sql表中导入csv文件的选定列

mysql - 符合条件的行的百分比

java - 在 JDBC 的 QUERY WHERE 子句中指定变量名

mysql - 每次 MS Access 发生任何更改时,将数据从 MS Access 数据库传输到 Mysql 数据库

php - 单选按钮验证器

javascript - 使用 jQuery 加载 POST 表单

PHP MySQL 连接错误