3

How to add product to compare products using product id programmatically.

Please give me suggestions.

2

We can use Magento\Catalog\Model\Product\Compare\Item to add compared products. (We should inject this class to the constructor or can use a Dirty Playground)

Take a look the table catalog_compare_item in database. We need to add the customer id to the product compare item. AND, you also need to add the data to report_compared_product_index table - \Magento\Reports\Model\Product\Index\ComparedFactory.

    /** @var $compareItem \Magento\Catalog\Model\Product\Compare\Item */

    /** @var $compareFactory \Magento\Reports\Model\Product\Index\ComparedFactory */

    $productIds = [1,2, 4, 5]; // For example data.
    $customerId = 1; // For example data. Make sure the customer exists.
     foreach ($productIds as $productId) {
        $compareItem->setCustomerId($customerId);
        $compareItem->addProductData($productId);
        $compareItem->save();
        $compareItem->unsetData();

        $viewData = [
            'product_id' => $productId,
            'customer_id' => $customerId
        ];
        $compareFactory->create()->setData($viewData)->save();
    }
1
  • why this line: $compareItem->unsetData(); exists? Dec 16 '18 at 8:59
0
  1. Inject the following class in the constructor where you want to use it.

\Magento\Catalog\Model\Product\Compare\ListCompare

public function __construct(
....
....
\Magento\Catalog\Model\Product\Compare\ListCompare $listCompare,
....
) {
...
$this->listCompare = $listCompare;
...
}

2) use addProducts method of this class to add products to compare list.

$productIds = <your product Ids>;
$this->listCompare->addProducts($productIds);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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