当我收到产品集合时:
$collection = Mage::getModel('catalog/product')->getCollection();
我得到一个group_price键,但它是空的。 (产品有group_price)
Array
(
[entity_id] => 1
[entity_type_id] => 4
[attribute_set_id] => 2
[type_id] => simple
[sku] => 00000
......
[group_price] => Array
(
)
......
)
如果我加载产品,我可以获得group_price数据:
$product_id = '1';
$product = Mage::getModel('catalog/product')->load($product_id);
$group_price = $product->getData('group_price');
我尝试使用join()或joinTable()或joinLeft()与表'catalog_product_entity_group_price'进行不同的查询,但没有成功。
如何使用连接查询将group_price数据加入集合?
我想避免迭代集合来加载每个产品并获得group_price。
尝试在foreach循环中设置产品,然后获得组价
$collection = Mage::getModel('catalog/product')->getCollection();
foreach($collection as $product){
$product->setId($product->getId());
$group_price = $product->getData('group_price');
}
我扩展了产品集合类并添加了这个功能
public function addGroupPriceData()
{
if ($this->getFlag('group_price_added')) {
return $this;
}
$groupPrices = array();
$productIds = array();
foreach ($this->getItems() as $item) {
$productIds[] = $item->getId();
$groupPrices[$item->getId()] = array();
}
if (!$productIds) {
return $this;
}
/** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
$attribute = $this->getAttribute('group_price');
if ($attribute->isScopeGlobal()) {
$websiteId = 0;
} else if ($this->getStoreId()) {
$websiteId = Mage::app()->getStore($this->getStoreId())->getWebsiteId();
}
$adapter = $this->getConnection();
$columns = array(
'price_id' => 'value_id',
'website_id' => 'website_id',
'all_groups' => 'all_groups',
'cust_group' => 'customer_group_id',
'price' => 'value',
'product_id' => 'entity_id'
);
$select = $adapter->select()
->from($this->getTable('catalog/product_attribute_group_price'), $columns)
->where('entity_id IN(?)', $productIds);
if ($websiteId == '0') {
$select->where('website_id = ?', $websiteId);
} else {
$select->where('website_id IN(?)', array('0', $websiteId));
}
foreach ($adapter->fetchAll($select) as $row) {
$groupPrices[$row['product_id']][] = array(
'website_id' => $row['website_id'],
'cust_group' => $row['all_groups'] ? Mage_Customer_Model_Group::CUST_GROUP_ALL : $row['cust_group'],
'price' => $row['price'],
'website_price' => $row['price'],
);
}
/* @var $backend Mage_Catalog_Model_Product_Attribute_Backend_Groupprice */
$backend = $attribute->getBackend();
foreach ($this->getItems() as $item) {
$data = $groupPrices[$item->getId()];
if (!empty($data) && $websiteId) {
$data = $backend->preparePriceData($data, $item->getTypeId(), $websiteId);
}
$item->setData('group_price', $data);
}
$this->setFlag('group_price_added', true);
return $this;
}