Context: we have a project which uses M2E so our client can sell on eBay. For easy reference, we've added custom columns to the product grid in the admin panel so that the eBay item ID is displayed next to the other product details.
The above all works fine, no problems.
The problem is that occasionally eBay issues a new item ID for an item for some reason or another, and then we have two eBay item IDs for the same product. This has just been flagged as an issue because when we use joinField to add the item ID to the product collection, it's grabbing the first ID it finds, not the latest one.
So what we want to do is grab the newest eBay item ID instead of the first one found but I'm struggling to find a way to make this work within Magento. Straight SQL would be no problem, but I'm a little less skilled with Magento DB queries.
This is the code we're using to join the eBay item ID table at present:
$collection->joinField('ebay_item_id', 'm2epro_ebay_item', 'item_id', 'product_id=entity_id', null, 'left');
This is what we tried adding to make it work (no luck):
$collection->addAttributeToSort('m2epro_ebay_item.update_date', 'DESC');
These are the relevant column headings in the table we're joining:
id (row ID)
item_id (eBay item ID)
product_id (Magento product ID)
update_date (last updated)
create_date (creation date)
It could be sorted by any of ID, update_date, or create_date, but I can't get my head around how to get it to do it within the Magento architecture.
So any help or pointers would be appreciated.
Edited to add:
class Digitalsix_CustomGrid_Model_Adminhtml_Observer {
public function onBlockHtmlBefore(Varien_Event_Observer $observer) {
$block = $observer->getBlock();
if (!isset($block)) {
return;
}
switch ($block->getType()) {
case 'adminhtml/catalog_product_grid':
$block->addColumn('ebay_item_id', array(
'header' => Mage::helper('catalog')->__('Ebay ID'),
'width' => '80px',
'index' => 'ebay_item_id',
'filter' => false,
));
break;
}
}
public function onEavLoadBefore(Varien_Event_Observer $observer) {
$collection = $observer->getCollection();
if (!isset($collection)) {
return;
}
if (is_a($collection, 'Mage_Catalog_Model_Resource_Product_Collection')) {
$collection->getSelect()->group('e.entity_id');
if (!$collection->fieldAlreadyJoined("ebay_item_id")) {
$collection->joinField('ebay_item_id', 'm2epro_ebay_item', 'item_id', 'product_id=entity_id', null, 'left');
}
}
}
}