Magento 2 Dapatkan id kategori menggunakan judul kategori


11

Saya ingin mendapatkan id kategori dengan hanya menggunakan judul kategori dengan menggunakan fungsi semacam ini.

->load($categoryTitle, 'title')
->getId();

Use case: Dapatkan id kategori berdasarkan judul dan masukkan data id ke array dalam skrip migrasi.

Jawaban:


18

Anda dapat melakukannya melalui koleksi:

Pertama, Anda perlu menyuntikkan CategoryFactorykonstruktor kelas Anda.

Magento 2.0 & 2.1:

public function __construct(
    ...
    \Magento\Catalog\Model\CategoryFactory $categoryFactory
) {
    $this->_categoryFactory = $categoryFactory;
    parent::__construct(...);
}

Kemudian di tempat lain di kelas Anda yang dapat Anda lakukan:

$collection = $this->_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
}

Magento 2.2:

public function __construct(
    ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collecionFactory
) {
    $this->_collectionFactory = $collecionFactory;
    parent::__construct(...);
}

Kemudian di tempat lain di kelas Anda yang dapat Anda lakukan:

$collection = $this->collecionFactory
                ->create()
                ->addAttributeToFilter('name',$categoryTitle)
                ->setPageSize(1);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
}

Punya kesalahan PHP Kesalahan fatal: Panggil ke metode tak terdefinisi Magento \ Catalog \ Model \ CategoryFactory :: getCollection ()
— kilis

1
@kilis lihat pembaruan saya, Anda perlu menggunakan DI untuk menyuntikkan kelas itu;)
— Raphael di Digital Pianism

Untuk kasus penggunaan saya, saya memerlukan fungsi semacam ini $ collection = $ this -> _ objectManager-> create ('\ Magento \ Catalog \ Model \ CategoryFactory') -> getCollection () -> addAttributeToFilter ('title', $ categoryTitle) - > setPageSize (1);
— kilis

1
@kilis baik itu praktik buruk untuk menggunakan objek manager secara langsung, Anda harus selalu menggunakan injeksi dependensi
— Raphael di Digital Pianism

ya aku tahu. Skrip upgrade proyek kami dirancang seperti itu: /
— kilis

4

Ini dapat dilakukan dengan menggunakan kontrak layanan yang dianggap sebagai praktik terbaik.

protected $categoryList;

    /**
     * @var SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @var FilterBuilder
     */
    protected $filterBuilder;

public function __construct(
        ------------
        CategoryListInterface $categoryList,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        -----------------
    )
    {
        $this->categoryList = $categoryList;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->filterBuilder         = $filterBuilder;
        parent::__construct(----------);
    }

public function getNameCategory()
    {
        $enableFilter[] = $this->filterBuilder
            ->setField(\Magento\Catalog\Model\Category::KEY_NAME)
            ->setConditionType('like')
            ->setValue(self::CATEGORY_NAME_HELP) // name of the categroy on const
            ->create();


        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilters($enableFilter)
            ->create();

        $items = $this->categoryList->getList($searchCriteria)->getItems();

        if(count($items) == 0)
        {
            return FALSE;
        }

        foreach ($items as $helpCategory)
        {
            $CategoryId = $helpCategory->getId()
        }
return $CategoryId;
    }

+1 Untuk bagian praktik terbaik
— Akif

3

Anda dapat melakukannya dengan sederhana name,

$title = 'womens';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name',$title);
echo "<pre>";
print_r($collection->getData());
exit;

Bukan untuk penggunaan FE, perluas fungsionalitas skrip yang diperlukan.
— kilis

Anda hanya mengatakan judul, saya telah memperbarui jawaban saya.
— Rakesh Jesadiya

2

Coba Kode Di Bawah Ini Untuk File Phtml:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$_categoryFactory = $objectManager->get('Magento\Catalog\Model\CategoryFactory');

$categoryTitle = 'Outdoor'; // Category Name

$collection = $_categoryFactory->create()->getCollection()->addFieldToFilter('name', ['in' => $categoryTitle]);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
}

1

Saya mendapatkannya dengan bantuan dari kolase saya

$this->_objectManager->get('Magento\Catalog\Model\CategoryFactory')->create()->getCollection()
        ->addFieldToSelect('name')
        ->addFieldToFilter('name', ['in' => $categoryTitle]);

:) Karena koleksi hanya akan mengembalikan catatan yang Anda inginkan, Anda dapat mengambil satu-satunya hasil dengan ->getFirstItem()pada kode di atas


0

Untuk memperbaiki itu dalam skrip yang berfungsi saya sarankan menggunakan yang berikut ini

$obj = $bootstrap->getObjectManager();
$_categoryFactory = $obj->get('Magento\Catalog\Model\CategoryFactory');
$collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('title',$categoryTitle)->setPageSize(1);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getCategoryId();
}

Sunting: Saya membuat dan menguji sebuah skrip. Saya membuat file di /scripts/file.php

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

// Set the state (not sure if this is neccessary)
$obj = $bootstrap->getObjectManager();
$_categoryFactory = $obj->get('Magento\Catalog\Model\CategoryFactory');
$categoryTitle = 'Test';
$collection = $_categoryFactory->create()->getCollection()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);
if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
    echo $categoryId; 
}

Mencoba kode Anda, tetapi mengubah baris pertama menjadi $ obj = $ this -> _ objectManager; Mendapat [Magento \ Framework \ Exception \ LocalizedException] Nama atribut tidak valid: kesalahan judul
— kilis

Ketika Anda mendapatkan kesalahan itu, Anda tidak menggunakan skrip saya.
— Kay Int Veen

Saya baru saja menambahkan skrip yang sudah teruji sepenuhnya. tolong periksa itu. pasti akan berhasil!
— Kay Int Veen

0

Saya berhasil menulis metode saya sendiri (lebih efisien):

$entityTypeId = \Magento\Catalog\Setup\CategorySetup::CATEGORY_ENTITY_TYPE_ID;
$row = $this->queryF("SELECT * FROM `eav_attribute` WHERE `entity_type_id` = $entityTypeId AND `attribute_code` = 'name'", 1);
$nameAttributeId = $row['attribute_id'];
$categoryNames = $this->queryF("SELECT * FROM `catalog_category_entity_varchar` WHERE `attribute_id` = '$nameAttributeId'");
$this->categoryNameIdMap = [];
foreach ($categoryNames as $item) {
    $id = $item['entity_id'];
    $title = $item['value'];
    $this->categoryNameIdMap[$title] = $id;
}

Kode ini cache semua judul: id ke dalam array, dan hanya kueri 2 kali.

Bekerja untukku. Lebih mudah digunakan!


0

Pertama, Anda perlu menyuntikkan kelas koleksi pabrik

public function __construct(
    ...
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collecionFactory ) {
    $this->_collectionFactory = $collecionFactory;
    parent::__construct(...); }

Setelah itu di dalam metode Anda, Anda bisa melakukan ini,

$categoryTitle = 'Men';
$collection = $this->_categoryCollectionFactory->create()->addAttributeToFilter('name',$categoryTitle)->setPageSize(1);

if ($collection->getSize()) {
    $categoryId = $collection->getFirstItem()->getId();
}
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.