I have 3000+ products in a brand category. How do I programmatically move brand to brand collection?
If I move in the backend it will take some time. How do I move?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityYou can achieve this easily using a MySQL query.
As per as my suggestion this is the best way.
Magento saves product-category associations in the catalog_category_product table.
Step 1: Take a backup of the database. Mainly the catalog_category_product table.
Step 2: Run the below query for moving products from the old category to the new category.
SELECT {NEW_CAT_ID} cat,
product_id
,position
FROM catalog_category_product WHEREcategory_id
= {OLD_CAT_ID} AND product_id NOT IN ( SELECTproduct_id
FROM catalog_category_product WHERE category_id = {NEW_CAT_ID}));
Suppose, your new category id is 7, and the old category id is 4.
INSERT INTO catalog_category_product(
SELECT 7 cat, `product_id`, `position`
FROM catalog_category_product
WHERE `category_id` = 4
AND product_id NOT IN
(
SELECT `product_id`
FROM catalog_category_product
WHERE category_id = 7
)
);
Step 3: Delete records from the old category using a MySQL query:
Delete from catalog_category_product where category_id={OLD_CAT_ID};
Example:
Delete from catalog_category_product where category_id=4;
Let's say you have the category you want to move called $category
and the category you want to be the parent of $category
...Let's call that $parentCategory
.
you can do this from code:
Mage::getResourceSingleton('catalog/category')->changeParent($category, $parentCategory);
This will make $category
a child of $parentCategory
but it will add it as the first child of $parentCategory
.
If you want to move $category
after a certain chilc of $parentCategory
you need to do this:
Mage::getResourceSingleton('catalog/category')->changeParent($category, $parentCategory, $afterChildId);
where $afterChildId
is the id of a child category of $parentCategory
.
Here is an example.
You have this tree
- A
- B
- C
- D
And you want to make A a child of B.
Mage::getResourceSingleton('catalog/category')->changeParent($instanceOfCategoryA, $instanceOfCategoryB);
will result in
- B
- A
- C
- D
and
Mage::getResourceSingleton('catalog/category')->changeParent($instanceOfCategoryA, $instanceOfCategoryB, $idOfCategoryC);
will result in
- B
- C
- A
- D
Here is the query of Amit Bera for Magento 2
INSERT INTO catalog_category_product (category_id, product_id, position)
SELECT 100, `product_id`, `position`
FROM catalog_category_product
WHERE `category_id` = 726
AND product_id NOT IN
(
SELECT `product_id`
FROM catalog_category_product
WHERE category_id = 100
)
brand collection
a category or else?