仅使用类别名称查找是否存在类别

Ste*_*rek 3 import magento

我正在为Magento构建一个自定义产品导入模块,之前从未与Magento合作过.

我有一个包含所有产品的CSV文件.其中一列包含应使用斜杠分隔产品的类别.例如:

Jewelry / Rings / Diamond
Jewelry / Neckless / Diamond
Run Code Online (Sandbox Code Playgroud)

等.

我遇到的问题是钻石类别可以作为任何数量的父类别中的子类别存在.我的解决方案是打破路径(即expload($ categoryPath,"/"))

使用第一个例子(珠宝/戒指/钻石)我从商店根类别开始,检查它是否包含珠宝的子类别,如果它我得到该子类别的ID并递归地前往终点线,或者至少那是理论.

我遇到的问题就在这里......

$rootCategory = Mage::getModel('catalog/category') -> load($rootCategoryId);
$currentCategory = $rootCategory -> getChildrenCategories() -> loadByAttribute('name', $targetCategoryName);
Run Code Online (Sandbox Code Playgroud)

这引发了一个错误......"在一个非对象上调用成员函数getName()"...我假设因为getChildrenCategories()正在返回一个集合而我无法在其上调用loadByAttribute.

如果这对任何人都有意义,请告诉我如何仅使用名称从根类别加载子类别.我希望如果loadByAttribute无法加载类别(因为它不存在),它将返回False,然后我可以创建类别.


为了回应Pavels的建议,我尝试了:

$targetCategoryName = 'Jewelry';

$subCategories = $rootCategory
                    -> getChildrenCategories()
                    -> addAttributeToFilter('name',$targetCategoryName) 
                    -> setCurPage(1)
                    -> setPageSize(1)
                    -> load();

    $currentCategory = $subCategories
                    -> getFirstItem();
Run Code Online (Sandbox Code Playgroud)

$ currentCategory的名称是'dummy-category'.看起来过滤器不起作用.

Dre*_*ter 6

根据您的问题,我认为您需要根据父类别按名称查找类别,即仅搜索其子项?

如果是的话......

$childCategoryName = 'Bedroom';
$parentCategoryId = 10;

$parentCategory = Mage::getModel('catalog/category')->load($parentCategoryId);
$childCategory = Mage::getModel('catalog/category')->getCollection()
    ->addAttributeToFilter('is_active', true)
    ->addIdFilter($parentCategory->getChildren())
    ->addAttributeToFilter('name', $childCategoryName)
    ->getFirstItem()    // Assuming your category names are unique ??
;

if (null !== $childCategory->getId()) {
    echo "Found Category: " . $childCategory->getData('name');
} else {
    echo "Category not found";
}
Run Code Online (Sandbox Code Playgroud)

您使用原始代码处于正确的轨道上:

$currentCategory = $rootCategory -> getChildrenCategories() -> loadByAttribute('name', $targetCategoryName);
Run Code Online (Sandbox Code Playgroud)

但问题是$rootCategory->getChildrenCategories()返回一个集合,因此您需要对此进行过滤,而不是loadByAttribute对模型进行过滤.

但是,$rootCategory->getChildrenCategories()返回一个已加载的集合,因此您仍然无法过滤掉它.因此,我的答案中的代码略有不同 - 尽管它背后的逻辑相同.