如何在 Magento 中获取产品的类别
我正在尝试根据产品的类别将 Product_type 添加到我的 Magento Google Base 输出中,但我似乎无法这样做。我有以下代码:
// Get categories from product to include as product_type
$categoryIds = $object->getCategoryIds();
foreach($categoryIds as $categoryId) {
$category = Mage::getModel('catalog/category')->load($categoryId);
$this->_setAttribute('product_type', $category->getName(), 'text' );
}
问题是它返回所有类别,而不仅仅是产品所在的类别。有人有解决方案吗?
I'm trying to add product_type to my Magento Google Base output based on the product's categories, but I seem to be unable to. I have the following code:
// Get categories from product to include as product_type
$categoryIds = $object->getCategoryIds();
foreach($categoryIds as $categoryId) {
$category = Mage::getModel('catalog/category')->load($categoryId);
$this->_setAttribute('product_type', $category->getName(), 'text' );
}
The issue is that it returns all of the categories, not just the ones the product is in. Anyone have a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用上面 Rao 删除的源链接,我实际上找到了一个更好的答案:
Using the source link dropped by Rao above I actually found a better answer:
这完全没有经过测试。
然后您可以像遍历数组一样遍历
$categoryCollection
。来源
This is utterly not tested..
You can then loop through
$categoryCollection
like through an array.source
想要指出的是,如果您有一个产品对象可以从中获取类别 ID,那么 @Rao 的解决方案是最好的,因为它只进行一次 SQL 调用。
如果您只有类别 ID,则可以执行以下操作:
其中 array(1,2,3) 是您的类别。请注意,数组有整数,而不是字符串值,我发现 SQL 对此可能很挑剔。
还想指出,一次拉出一个类别的解决方案效率非常低,因为它会为循环的每次迭代进行 SQL 调用,例如:
Want to point out that the solution by @Rao is the best if you have a product object to get category ID's from as it makes only one SQL call.
If you just have category id's, you can do the following:
Where array(1,2,3) are your categories. Note that the array has integers, not string values, I found that SQL can be picky about that.
Also wanted to point out that solutions pulling one category at a time are very inefficient as it makes an SQL call for every iteration of the loop e.g.:
获取产品的所有类别
Get all Categories of the Product
Rao 的解决方案尝试加载所有属性,这意味着大量查询和联接,但您只需要一个
product_id
来加载其类别。所以你可以这样做:这不会加载产品并会给你类别。
Rao's solution tries to load all the attributes which means lots of queries and joins but you only need a
product_id
to load it's categories. So you can do this:This will not load the product and will give you the categories.
此代码在 Magento 2 的 phtml 文件中工作
This code work in phtml file in Magento 2