Magento:如何将两个产品集合合并为一个?

问题描述 投票:0回答:5

如果我有两个产品系列,有没有办法将它们合并为一个?

例如(我的最终目的并不是要得到两只猫的集合,这只是为了说明问题):

$collection1 = Mage::getModel('catalog/category')->load(148)->getProductCollection();
$collection2 = Mage::getModel('catalog/category')->load(149)->getProductCollection();

$merged_collection = merge_collections($collection1,$collection2);

如有任何帮助,我们将不胜感激!

php magento collections
5个回答
26
投票

假设您希望分组在一起的项目具有相同类型并且存在于数据库中,那么您可以执行以下操作:

$collection1 = Mage::getModel('catalog/category')->load(148)->getProductCollection();
$collection2 = Mage::getModel('catalog/category')->load(149)->getProductCollection();

$merged_ids = array_merge($collection1->getAllIds(), $collection2->getAllIds());
// can sometimes use "getLoadedIds()" as well

$merged_collection = Mage::getResourceModel('catalog/product_collection')
    ->addFieldToFilter('entity_id', array('in' => $merged_ids))
    ->addAttributeToSelect('*');

这里我知道按

entity_id
进行过滤,因为这是产品的关键字段,就像大多数实体类型一样,一些平面表具有不同的主键。通常,您可以使用集合的
getIdFieldName()
方法之一来概括这一点。在这种情况下,产品是一个不好的例子,因为它的 ID 字段名称未正确填写。


15
投票

Magento 中几乎每个(或每个?)集合都继承自“Varien Data Collection”。集合是保存另一种类型的对象的特殊对象。没有合并集合的方法,但您可以将适当类型的其他项目添加到集合中。 这样的代码应该可以让您到达您想去的地方,尽管可能有更有效的方法来循环和进行实际的合并。

$collection1 = Mage::getModel('catalog/category')->load(148)->getProductCollection(); $collection2 = Mage::getModel('catalog/category')->load(149)->getProductCollection(); //load an empty collection (filter-less collections will auto-lazy-load everything) $merged = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter('entity_id',-1); //add items from the first collection foreach($collection1 as $item) { $merged->addItem($item); } //add items from the second collection foreach($collection2 as $item) { //magento won't let you add two of the same thing to a collection //so make sure the item doesn't already exist if(!$merged->getItemById($item->getId())) { $merged->addItem($item); } } //lets make sure we got something foreach($merged as $product) { var_dump($product->getName()); }



5
投票

foreach ($collection1 as $item){ $collection2->addElem($item); }



3
投票

$products = Mage::getModel('catalog/product'); $_collection = $products->getCollection(); ->addCategoryFilter(2) ->load();

或尝试使用“addItem”将结果添加到集合中。另请参阅 
Magento wiki


-1
投票

$collection = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect('name') ->addAttributeToSelect('sku'); $collection->getSelect() ->join( 'catalog_category_product', 'product_id=entity_id', array('category_id') ) ->where('catalog_category_product.category_id IN (?)', $categories);

© www.soinside.com 2019 - 2024. All rights reserved.