I’m building a custom product import module for Magento and have never worked with Magento before in any regard.
I have a CSV file that contains all of the products. One of the columns contains the Category that the product should be assigned to separated by slashes. Ex:
Jewelry / Rings / Diamond
Jewelry / Neckless / Diamond
ect.
The problem I have is that the Diamond category can exist as a sub category in any number of parent categories. My solution was to break the path up (i.e. expload($categoryPath, “/”))
Using the first example (Jewelry / Rings / Diamond) I start at the stores root category and check to see if it contains a subcategory of Jewelry, if it does i get the ID of that subcategory and recursively make my way to the finish line, or at least that’s the theory.
The problem I’m running into is right here…
$rootCategory = Mage::getModel('catalog/category') -> load($rootCategoryId);
$currentCategory = $rootCategory -> getChildrenCategories() -> loadByAttribute('name', $targetCategoryName);
This throws me an error …”Call to a member function getName() on a non-object in”… I assume because getChildrenCategories() is returning a collection and i can not call loadByAttribute on it.
If this makes sense to anyone, please let me know how I can load a subcategory from the root category by using only the name. I was hoping that if loadByAttribute fails to load the category (because it does not exist) that it would return False and i can then create the category.
In response to Pavels suggestion i tryed :
$targetCategoryName = 'Jewelry';
$subCategories = $rootCategory
-> getChildrenCategories()
-> addAttributeToFilter('name',$targetCategoryName)
-> setCurPage(1)
-> setPageSize(1)
-> load();
$currentCategory = $subCategories
-> getFirstItem();
The name of $currentCategory is ‘dummy-category’. It would seem the filter is not working.
Based on your question, I think you need to find a category by name based on a parent category i.e. only search its children?
If so then…
You were kind of on the right track with your original code:
The problem though is that
$rootCategory->getChildrenCategories()returns a collection so you would need to filter this as opposed toloadByAttributewhich would work against a model.But,
$rootCategory->getChildrenCategories()returns a loaded collection so you would still not be able to filter that unfortunately. Hence the code in my answer is slightly different – though same logic behind it.