2012-10-03 39 views
3

我正在爲Magento構建一個定製產品導入模塊,並且在任何方面都從未與Magento合作過。使用類別名稱查找是否存在類別

我有一個包含所有產品的CSV文件。其中一列包含應將產品分配的類別以斜線分隔。例如:

Jewelry/Rings/Diamond 
Jewelry/Neckless/Diamond 

等。

我遇到的問題是鑽石類別可以作爲任何數量的父類別的子類別存在。我的解決方案是打破路徑(即expload($ categoryPath,「/」))

使用第一個示例(珠寶/戒指/鑽石)我從商店根類別開始,並檢查它是否包含珠寶的子類別,如果它是我得到該子類別的ID並遞歸地通往終點線,或者至少這是理論。

我遇到的問題是在這裏...

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

這引發了我的錯誤......「呼籲在非對象的成員函數的getName()」 .. 。我假設因爲getChildrenCategories()正在返回一個集合,我無法調用它的loadByAttribute。

如果這對任何人都有意義,請讓我知道如何通過使用名稱從根類別加載子類別。我希望如果loadByAttribute無法加載類別(因爲它不存在),它會返回False,然後我可以創建類別。


針對Pavels建議我tryed:

$targetCategoryName = 'Jewelry'; 

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

    $currentCategory = $subCategories 
        -> getFirstItem(); 

$ currentCategory的名稱是 '僞類'。這似乎是過濾器不工作。

回答

6

根據你的問題,我認爲你需要基於一個父類,即只有搜索它的孩子尋找通過名稱類別?

如果是的話...... hellip;

$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"; 
} 

你是那種在正確的軌道與你的原代碼:

$currentCategory = $rootCategory -> getChildrenCategories() -> loadByAttribute('name', $targetCategoryName); 

的問題是,雖然$rootCategory->getChildrenCategories()返回集合,所以你將需要過濾此,而不是loadByAttribute這將對模型起作用。

但是,$rootCategory->getChildrenCategories()返回一個已加載的集合,所以你仍然無法過濾不幸的。因此,我的答案中的代碼略有不同 - 儘管它背後的邏輯相同。

2

試試這個

<?php 
$name = 'Furniture'; 
$categories = Mage::getResourceModel('catalog/category_collection'); 
$categories->addAttributeToFilter('is_active', 1) 
     ->addAttributeToFilter('name', $name) 
     ->setCurPage(1)->setPageSize(1) 
     ->load(); 

if ($categories->getFirstItem()) { 
    $category = $categories->getFirstItem(); 
    echo $category->getId(); 
} else { 
    echo 'No category exists with the name ' . $name; 
} 
+0

感謝您的幫助,我仍然有一些問題,我添加到原來的職位。 –