如何在Magento 2中根据分类ID获取父分类ID?
如何在Magento 2中通过分类ID获取父分类ID(使用ObjectManager)
你已经成功拿到商品的分类ID数组了,接下来只需要在循环里加载每个分类对象,就能轻松获取对应的父分类ID啦。虽然官方一直强调尽量避免直接使用ObjectManager,但既然需求明确要求用它,那咱们直接上可用的实现方案:
完整代码示例
$product_id = 101; // 示例商品ID $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // 获取商品对象 $productRepository = $objectManager->create('\Magento\Catalog\Model\ProductRepository'); $product = $productRepository->getById($product_id); // 获取商品所属所有分类ID数组 $category_ids = $product->getCategoryIds(); // 遍历分类ID,获取每个分类的父分类ID foreach ($category_ids as $cat_id) { // 加载指定ID的分类对象 $category = $objectManager->create('\Magento\Catalog\Model\Category')->load($cat_id); // 获取父分类ID $parent_category_id = $category->getParentId(); // 可根据需求替换为你的业务逻辑,比如存储或进一步处理 echo '分类ID ' . $cat_id . ' 的父分类ID是:' . $parent_category_id . '<br>'; }
关键细节说明
- 这部分逻辑和Magento 1的思路基本一致,只是把Magento 1里的
Mage::getModel换成了ObjectManager创建\Magento\Catalog\Model\Category实例 getParentId()方法直接返回父分类的整数ID,用法和Magento 1完全相同- 帮你修正了原代码里循环变量名不一致的小问题(原来循环用
$cat_ids但内部用$cat_id,现在统一为$cat_id避免报错)
额外提示(你已知但还是提一句)
官方不推荐直接用ObjectManager是因为它会破坏依赖注入的封装性,不利于代码的可维护性和测试。如果后续需求允许,建议通过构造函数注入\Magento\Catalog\Model\CategoryFactory和\Magento\Catalog\Model\ProductRepository来实现,但就当前需求来说,上面的代码完全可以正常运行。
内容的提问来源于stack exchange,提问作者AlexanderGR
相关产品推荐
相关产品推荐

