Magento 2-获取特定父类别的子类别


9

我想做的是获取特定父类别的所有子类别。我假设最好的方法是使用父母的ID和返回的那些子类别,我也想抓住他们的子类别。


之后如何获得分类的儿童类别$subcats = $subcategory->getChildrenCategories();
Kamlesh Yaduwanshi

Answers:


16

检查以下示例,使用objectManager使用父类别ID获取特定父类别的所有子类别的列表。

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $catId = 2;  //Parent Category ID
    $subCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
    $subCats = $subCategory->getChildrenCategories();
    $_helper = $this->helper('Magento\Catalog\Helper\Output');
?>
<ul class="sub-cat-ul">
    <?php
    foreach ($subCats as $subcat) {
        $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
        $subcaturl = $subcat->getUrl();
        $_imgHtml = '';

        if ($_imgUrl = $_category->getImageUrl()) {
            $_imgHtml = '<img src="' . $_imgUrl . '" />';
            $_imgHtml = $_helper->categoryAttribute($_category, $_imgHtml, 'image');
        } ?>
        <li class="cat-li">
            <div class="cat-image">
                <a href="<?php echo $subcaturl ?>"><?php echo $_imgHtml;?></a>
            </div>
            <div class="info">
                <h4><?php echo $subcat->getName(); ?></h4>
                <a class="link" href="<?php echo $subcaturl ?>"><?php /* @escapeNotVerified */ echo __('View more') ?></a>
            </div>
        </li>
    <?php } ?>
</ul>

=====

检查以下示例,以使用存储库使用父类别ID列出特定父类别的所有子类别。

首先在构造中添加CategoryRepository

<?php
    protected $categoryRepository;

    public function __construct(
        \Magento\Catalog\Model\CategoryRepository $categoryRepository
    ) {
        $this->categoryRepository = $categoryRepository;
    }
?>

现在,您可以使用以下方式:

<?php
    $categoryId = [YOUR_CATEGORY_ID];
    $category = $this->categoryRepository->get($categoryId);
    $subCategories = $category->getChildrenCategories();
    foreach($subCategories as $subCategory) {
        echo $subCategory->getName();

        /* For Sub Categories */
        if($subcategorie->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subCategory->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategory) {
            echo $childSubcategory->getName();
        }
     }
    }
?>

2
为我工作...!
Devidas

2
您不应该这样使用objectManager。参考:magento.stackexchange.com/questions/117098/...
弗兰克·格鲁特

14

您需要在类中添加一个依赖项\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory

像这样:

protected $categoryCollectionFactory;
public function __construct(
    ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
    ...
) {
    ...
    $this->categoryCollectionFactory = $categoryCollectionFactory;
    ...
}
public function getDescendants($category, $levels = 2)
{
    if ((int)$levels < 1) {
        $levels = 1;
    }
    $collection = $this->categoryCollectionFactory->create()
          ->addPathsFilter($category->getPath().'/') 
          ->addLevelFilter($category->getLevel() + $levels);
    return $collection;
}

现在,您只需要getDescendants使用$category对象作为参数以及子类别所需的级别数(在本例中为2)调用该方法。


我正在尝试一下,但是您能否阐明在phtml文件中应使用什么代码?
保罗

您需要将此代码添加到您的块类中,并且可以在phtml中使用$block->getDescendents($category, 2)where $category是主要类别。(我不知道你从哪里得到的)。
马吕斯

@Marius Hey Marius,我知道一篇老文章,但是如何弄清楚……应该在哪里?
乔恩·荷兰

@Marius Super答案(y)
sheraz khan

10

始终尝试使用存储库。这是一个例子。

CategoryRepository通过构造注入

protected $categoryRepository;

public function __construct(
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
    $this->categoryRepository = $categoryRepository;
}

现在,您可以使用以下方式:

$parent_category_id = 3;
$categoryObj = $this->categoryRepository->get($parent_category_id);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategorie) {
    echo '    --> '.$subcategorie->getName().'<br/>';
}

对于2级子类别:

$categoryObj = $this->categoryRepository->get($parent_category_id);
$subcategories = $categoryObj->getChildrenCategories();
foreach($subcategories as $subcategorie) {
    echo '    --> '.$subcategorie->getName().'<br/>';
    if($subcategorie->hasChildren()) {
        $childCategoryObj = $this->categoryRepository->get($subcategorie->getId());
        $childSubcategories = $childCategoryObj->getChildrenCategories();
        foreach($childSubcategories as $childSubcategorie) {
            echo '        --> '.$childSubcategorie->getName().'<br/>';
        }
    }
}

这只会给您1级子类别。OP要求2个等级。
马里乌斯

1
使用接口比直接使用存储库模型更好。\Magento\Catalog\Api\CategoryRepositoryInterface
安德烈(Andrei)

如何将getChildrenCategories限制为仅4个?我需要父类别的前4
个子

2
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category 
    $catId = $category->getId(); // Parent Category ID
        $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
$subcats = $subcategory->getChildrenCategories();
        $categoryHelper = $this->getCategoryHelper();    
    <div class="category_bg mobile">
            <ul id="main_cat_bg" class="main_cat_bg">
                <?php
                $cat_togg = 0;
                foreach ($subcats as $subcat) {
                    if (!$subcat->getIsActive()) {
                        continue;
                    }
                    $_category = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
                    //$_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
                    $helper    = $this->helper('SR\CategoryImage\Helper\Category');
                    $subcaturl = $subcat->getUrl();
                    $imageUrlthum = $helper->getImageUrl($_category->getData('thumbnail'));
                    //$imageUrlthum = resize($_category->getData('thumbnail'),153,153);
                    //$cat_desc = $_category->getCatDescription();
                    $_imgHtml = '';
                    if ($imageUrlthum) {
                        $_imgHtml = '<img src="' . $imageUrlthum. '" />';

                        //$_imgHtml = $_outputhelper->categoryAttribute($_category, $_imgHtml, 'image');
                /* @escapeNotVerified */
                    } 
                    ?>
                    <li>
                        <div class="sub_cat_content_main">
                            <div class="cat_image_text">
                                <a href="<?php echo $subcaturl ?>">
                                    <?php echo $_imgHtml;?>
                                    <!--<div class="desicription_part">-->
                                    <?php //echo $cat_desc; ?>
                                    <!--</div>-->
                                </a>
                               <div class="sub_name_bg">                
                                    <a href="<?php echo $subcaturl ?>">
                                        <?php echo $subcat->getName(); ?>
                                    </a>
                                </div>
                                <!-- Start 3rd Level Chiled Category-->
                                <?php
                                    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                                    $object_managertwo = $objectManager->create('Magento\Catalog\Model\Category')->load($subcat->getId());
                                    $subcatslevelthird = $object_managertwo->getChildrenCategories();
                                ?>
                                <?php if ($subcatslevelthird->count() > 0) { ?>
                                <ul class="sub_cat_bg">
                                    <?php
                                    foreach ($subcatslevelthird as $subcatthird) {
                                        $_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
                                        $subcaturl = $subcatthird->getUrl();
                                        ?>
                                        <li class="cat_image_bg">
                                            <a class="level-top" href="<?php //echo $subcaturl ?>">
                                                <span><?php //echo $subcatthird->getName(); ?></span>
                                            </a>
                                            <div class="child_name_bg">
                                                <span><?php echo $subcatthird->getName(); ?></span>
                                            </div>

                                        <!-- Start 4th Level Chiled Category-->
                                        <?php
                                            $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                                            $object_managerthree = $_objectManager->create('Magento\Catalog\Model\Category')->load($subcatthird->getId());
                                            $subcatslevel = $object_managerthree->getChildrenCategories();
                                        ?>
                                        <?php if ($subcatslevel->count() > 0){?>
                                        <ul class="chiled_cat_bg">
                                            <?php
                                            foreach ($subcatslevel as $subcatlevel) {
                                                $_outputhelper = $this->helper('Magento\Catalog\Helper\Output');
                                                $subcaturl = $subcatlevel->getUrl();
                                                ?>
                                                <li class="cat_image_bg">
                                                    <a class="level-top" href="<?php echo $subcaturl ?>">
                                                        <span><?php echo $subcatlevel->getName(); ?></span>
                                                    </a>
                                                </li>

                                            <?php } ?>
                                        </ul>
                                        <?php } ?>
                                        <!-- End 4th level Chiled Category-->
                                        </li>
                                    <?php } ?>
                                </ul>
                                <?php } ?>
                                <!-- End 3rd level Chiled Category-->
                            </div>
                        </div>
                    </li>
                <?php } ?>
            </ul>
             <div id="view_more">
                View more
            </div>
        </div>

我想按子类别对子类别进行排序,请帮忙吗?
卡姆莱什·亚度万希

您需要使用和获取类别名称的类别ID
Baharuni Asif

2

使用下面的代码来获取特定类别的所有活动子类别。

函数getChildCategories($ categoryId)给出所有子类别。其中$ categoryId-是父类别ID

<?php
namespace YourModuleName\CategoryLink\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\CategoryFactory;


/**
 * Category link block
 */
class Link extends Template
{
    /**
     * @var Magento\Catalog\Model\CategoryFactory
     */
    protected $_categoryFactory;


    /**
     * 
     * @param Context $context
     * @param array $data
     */
    public function __construct(
        Context $context, 
        CategoryFactory $categoryFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_categoryFactory = $categoryFactory;
      }

    /**
     * Get children categories 
     * 
     * @param $categoryId Parent category id
     * @return Magento\Catalog\Model\ResourceModel\Category\Collection
     */
    public function getChildCategories($categoryId)
    {

        $_category = $this->_categoryFactory->create();

        $category = $_category->load($categoryId);

        //Get category collection
        $collection = $category->getCollection()
                ->addIsActiveFilter()
                ->addOrderField('name')
                ->addIdFilter($category->getChildren());
        return $collection;
    }

} 

$ category-> getChildren()-这将提供所有分类类别的ID。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.