3

I would like to programmatically assign a product collection to a category. This is my product collection for example

$_productCollection = Mage::getModel('catalog/product')
->getCollection()
->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
->addAttributeToSelect('*')
->addAttributeToFilter('category_id', array(
        array('finset' => '345'),
        array('finset' => '320')
        )
)
->addAttributeToSort('created_at', 'desc');
$_productCollection->getSelect()->group('e.entity_id');

I want these products to be assigned to a category id. Is it possible?

3
  • 1
    check this link stackoverflow.com/questions/6491548/…
    – Mujahidh
    Nov 30, 2016 at 4:26
  • the link you provided is for a single product. What about a product collection? Do I have to loop it?
    – Doni
    Nov 30, 2016 at 7:39
  • if you know the categor_ id and product_ids you can use this Mage::getSingleton('catalog/category_api') ->assignProduct($category->getId(),$p‌​roduct->getId());
    – Mujahidh
    Nov 30, 2016 at 8:41

2 Answers 2

3

I will add an answer with the help of the above link i posted.

$collection = Mage::getModel('catalog/product')->getCollection();

foreach ($collection as $product_all) {

    $product_id  =  $product_all['entity_id'];//This will give you the product id

    $product    = Mage::getModel('catalog/product');
    $product ->load($product_id);
    $categories = $product->getCategoryIds();


    $categories[] = 152;//HERE YOU CAN ASSIGN WHATEVER CATEGORY ID YOU WANT TO UPDATE

    $product->setCategoryIds($categories);
    $product->save();
}
1
0

Best way to assign a category to product collection. Reference from core code - app\code\core\Mage\Catalog\Model\Resource\Category.php

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$categoryProductTable = Mage::getSingleton('core/resource')->getTableName('catalog/category_product');
$productData = array();$position=0;
foreach ($_productCollection as $product) {
    $productData[] = array(
        'category_id' => (int)$catId,
        'product_id'  => (int)$product->getId(),
        'position'    => (int)$position
    );
}

$write->insertMultiple($categoryProductTable, $productData);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.