开发者

Magento Zend_Db_Adapter_Abstract::update problem

I've written a module that can take in a CSV file and add data to the sales_flat_order table (code below). Despite my skepticism and lack of knowledge in interacting directing with the DB through Magento, I was able to successfully update the necessary columns in the table. However, every time I run the code, it updates the rows but always adds one extra row to the table with all null values. I've tried printing out the raw SQL and I don't see any extraneous SQL calls, yet it keeps doing it.

Here are the important snippets of code that should help explain what I'm doing. Hopefully this is a known issue someone else has run into and can point me in the right direction.

First, here's my 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>

As it says in the comments, I didn't provide any entities because I'm not using my own table (it initializes using the sales/order resource model (see blow)

Next, I added this to my system.xml file to add a file import box to the config:

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

Here's the backend_model class used in system.xml for the upload box:

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");
    }
}

And finally, the meat of it all is the Model Resource class that does all the work. You can see here that I call _init('sales/order') in the constructor so that I can piggyback on the sales_order resource model and not have to make a separate DB connection (I'm assuming this is ok...it's working, but let me know if this is a bad idea)

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 |开发者_如何学C| 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']));
        }
    }
}

I cut out a lot of my debug statements to simplify it, but it's important to note that if I echo the size of the $importData array it is always 3 as expected from my CSV. If I add logging to Zend_Db_Adapter_Abstract to print each SQL statement it runs, it only runs 3. So I don't know why the extra line is being inserted.

Thanks in advance for any help!


I'm not 100% sure the reason why this was happening, but I have found a solution. I believe this is caused by the fact that, by default, any Mage_Core_Model_Config_Data object stores its values in the core_config_data table. Since I initialized this to use my own resource model which actually piggybacks on the sales/order resource model, it got confused and tried to save bogus information to the sales/order table.

To fix it, I did the following:

First, in the constructor for the backend_model class used in the system.xml, set the _dataSaveAllowed flag to false:

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

Next, instead of using _afterSave to process the CSV import, use _beforeSave (_afterSave isn't called when you don't allow saving of the data)

This appears to have resolved my issues, but I welcome any comments/suggestions if my method is flawed. I'm still new at this, so any experienced insight is always appreciated :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜