【发布时间】:2015-12-14 12:43:24
【问题描述】:
我有一个名为warehouse 的产品自定义属性,类型为下拉。
为了通过模型在日期之间加载Sku => Warehouse(为每个产品分配值)更新;我执行以下操作:
// Load warehouse attribute options
$warehouse_options = array();
$options = array();
$attribute = Mage::getSingleton('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'warehouse');
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);
}
$attribute = null;
foreach ($options as $option) {
$warehouse_options[$option['value']] = $option['label'];
}
$options = null;
// Load all products updated since last sync
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('updated_at', array(
'from' => $datetime_from,
'to' => $datetime_to,
'date' => true
));
// Init results
$results = array(
'ServerDateTime' => $datetime_now,
'Mapping' => array()
);
// Build results
foreach ($collection as $p) {
$product = Mage::getModel('catalog/product')->load($p->getId());
$results['Mapping'][] = array(
'Sku' => $product->getSku(),
'Warehouse' => isset($warehouse_options[$product->getWarehouse()]) ? $warehouse_options[$product->getWarehouse()] : ''
);
$product = null;
}
$collection = null;
这可行,但加载每个产品时速度很慢,所以如果我有3000 产品,那就是3000+ 查询。
有没有办法对此进行优化,以便我能够以最少的查询和处理量加载所需的数据?
我尝试使用 addAttributeToSelect 来使用这样的集合:
$collection->addAttributeToSelect('sku', 'warehouse');
但是,返回的$collection->getData() 不包含字段warehouse。这是一个示例响应数组:
Array
(
[0] => Array
(
[status] => 1
[entity_id] => 4
[type_id] => simple
[attribute_set_id] => 4
[updated_at] => 2015-07-07 15:35:35
[sku] => C13S041061
)
【问题讨论】:
-
使用
addFieldToSelect而不是addAttributeToSelect。 -
不,
addAttributeToSelect是正确的,因为他使用的是 EAV 属性