0

Is there any way that I can assign products to category using SQL in code? Currently, Category Result Sets are too large, the request gets heavy, so unable to save a Category the traditional way.

2 Answers 2

2

Category and Products are mapped on catalog_category_product table.

Where there are 4 columns: entity_id, category_id, product_id, position.

Where entity_id is the auto-increment column .

So you can run this by Sql:

    INSERT INTO `catalog_category_product`(`category_id`, `product_id`) 
    VALUES ('category_id','product_id');

You can use it by simple corePHP program like:

  1. Create A temporary table on your database having 4 columns ('id', 'category_id', 'product_id', 'flag') and stored data.
  2. Create a PHP file on root, and Connect to database.
  3. SELECT from this temporary table and INSERT into catalog_category_product table and if update success update flag.
3
  • Hello, how to use it in program ?
    – devhs
    Apr 20, 2021 at 4:31
  • I hope Now you better Understand it.
    – smruti
    Apr 20, 2021 at 8:48
  • Thankyou for the answer
    – devhs
    Apr 20, 2021 at 9:25
0

You can also assign products to category programmatically by using CategoryLinkManagementInterface By this way.

  * @var CategoryLinkManagementInterface
  */
 protected $categoryLinkManagement;
 public function __construct(
     \Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
 ) {
     $this->categoryLinkManagement = $categoryLinkManagementInterface;
   }
public function execute()
 {
 $this->categoryLinkManagement->assignProductToCategories(
                 $Productsku,
                 $categoryIds
             );
 }

By Using object Manager

categoryLinkManagement = \Magento\Framework\App\ObjectManager::getInstance()
            ->get('Magento\Catalog\Api\CategoryLinkManagementInterface');
categoryLinkManagement->assignProductToCategories(
                $product->getSku(),
                $product->getCategoryIds()
            );


  
1
  • When there are more then 1000+ products to execute with this function it gets 504 not found error
    – devhs
    Apr 20, 2021 at 9:25

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.