I want to assign product problematically to category. Magento\Catalog\Api\CategoryLinkManagementInterface
using DI. below is snippet of code.
protected $categoryLinkManagement;
public function __construct(
\Magento\Framework\Stdlib\DateTime\Timezone $_stdTimezone,
\Magento\Framework\Stdlib\DateTime\DateTime $stdlibDateTime,
\Kensium\Newproduct\Model\CategoryLink $categoryLinkManagement,
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
) {
$this->_stdTimezone = $_stdTimezone;
$this->stdlibDateTime = $stdlibDateTime;
$this->categoryLinkManagement = $categoryLinkManagement;
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
/**
* Method executed when cron runs in server
*/
public function execute() {
$pid = array();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$newCategoryId = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('productlabels/newtodays/newcategoryid');
$saleCategoryId = $objectManager->create('\Magento\Framework\App\Config\ScopeConfigInterface')->getValue('productlabels/newtodays/salecategoryid');
$collection = $this->_productCollectionFactory->create();
$this->NewProducts($collection,$newCategoryId);
$this->SaleProducts($collection,$saleCategoryId);
}
private function getCategoryLinkManagement()
{
if (null === $this->categoryLinkManagement) {
$this->categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
->get('\Kensium\Newproduct\Model\CategoryLink');
}
return $this->categoryLinkManagement;
}
public function NewProducts($collection,$newCategoryId)
{
$today = $this->_stdTimezone->date()->format('Y-m-d H:i:s');
$lastday = date('Y-m-d h:m:s', strtotime($today."+90 days"));
$collection->addAttributeToSelect('*')
->addFieldToFilter('new_to', ['lteq' => $lastday]);
foreach($collection as $col):
if($col->getSku()):
$this->getCategoryLinkManagement()->assignProductToCategories(
$col->getSku(),
array($newCategoryId)
);
endif;
endforeach;
}
This work when product is assign to another category. but there is 2 problem
1)Product should assign to other category otherwise i will get error category doesn't contain product due to below code in
$this->getCategoryLinkRepository()->deleteByIds($categoryId, $productSku);
on Magento\Catalog\Model\CategoryLinkManagement :: assignProductToCategories()
2) This will remove product from other categories.
Is there any other option to achieve this?