Есть вопрос?
Зайди на форум

Поиск на сайте: Advanced

Denix - новый дистрибутив Linux. Русификация Ubuntu и установка кодеков

dkws.org.ua
Форум сайта dkws.org.ua
 
Главная    ТемыТемы    АльбомАльбом    РегистрацияРегистрация 
 ПрофильПрофиль   Войти и проверить личные сообщенияВойти и проверить личные сообщения   ВходВход 

Magento 2: получение коллекции продуктов

 
Начать новую тему Ответить на тему    Список форумов dkws.org.ua -> PHP
 
Автор Сообщение
den

Старожил


Зарегистрирован: 31.01.2006
Сообщения: 13870
Откуда: Кировоград, Украина

СообщениеДобавлено: Ср Ноя 04, 2020 12:15 pm    Заголовок сообщения: Magento 2: получение коллекции продуктов
Ответить с цитатой

1) Load product collection :

<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $productCollectionFactory;
protected $categoryFactory;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
\Magento\Catalog\Model\CategoryFactory $categoryFactory,
array $data = []
) {
$this->productCollectionFactory = $productCollectionFactory;
$this->categoryFactory = $categoryFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(3);
foreach ($collection as $product)
{
print_r($product->getData());
}
return $collection;
}
}


Firstly, change below all types of code as per requirement in getProductCollection() function.

2) Load product collection with specific attribute :


$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect(['name','sku']);
$collection->setPageSize(3);
foreach ($collection as $product)
{
print_r($product->getData());
}

3) Load product collection with all attribute :


$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(3);
foreach ($collection as $product)
{
print_r($product->getData());
}

4) Get product collection by multiple categories :

$categories = [1,2,3]; //category ids array
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoriesFilter(['in' => $categories]);
return $collection;

5) Get product collection by specific category :

$categoryId = '1';
$category = $this->categoryFactory->create()->load($categoryId);
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addCategoryFilter($category);
$collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;

6) Get product collection by product type :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('type_id', ['eq' => 'simple']);
$collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
$collection->getSelect()->limit(10);
return $collection;
You can add below text also as value of type_id for different product type filter :

simple = Filter of simple product
configurable = Filter of configurable product
grouped = Filter of grouped product
virtual = Filter of virtual product
bundle = Filter of bundle product

7) Get product collection by store id :
$storeid = 1;
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
return $collection;

Cool Get product collection by website ids :
$website_ids = [1,2];
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addStoreFilter($storeid);
$collection->addWebsiteFilter($websiteIds);
return $collection;

9) Filter Product Collection :
Is equal to :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['eq' => 1]);
Is not equal to :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('status', ['neq' => 1]);
Greater than :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gt' => 100]);
Greater than equal to :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['gteq' => 100]);
Less than :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lt' => 100]);
Less than equal to :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('price', ['lteq' => 100]);
Like :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['like' => '%Bag%']);
Not Like :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('sku', ['nlike' => '%Bag%']);
In Array :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['in' => [1,2]]);
Not in Array :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('entity_id', ['nin' => [1,2]]);
NULL :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['null' => true]);
NOT NULL :
$collection = $this->productCollectionFactory->create();
$collection->addAttributeToFilter('description', ['notnull' => true]);
Sort Product Collection :
Order by ASC :
$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'ASC');
OR

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'ASC');
Order by DESC :
$collection = $this->productCollectionFactory->create();
$collection->setOrder('sku', 'DESC');
OR

$collection = $this->productCollectionFactory->create();
$collection->getSelect->order('sku', 'DESC');
Set Limit Product Collection :
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->load();
Set Limit Product Collection with Current Page :
$collection = $this->productCollectionFactory->create();
$collection->setPageSize(50)->setCurPage(2)->load();
Count Product Collection :
$collection = $this->productCollectionFactory->create();
echo $collection->count();
Group by Product Collection :
$collection = $this->productCollectionFactory->create();
$collection->getSelect()->group('entity_id');
Print Collection Query :
$collection = $this->productCollectionFactory->create();
echo $collection->getSelect()->__toString();

Источник https://www.rohanhapani.com/magento-2-get-product-collection/
Вернуться к началу
Посмотреть профиль Отправить личное сообщение dhsilabs@jabber.ru
Показать сообщения:   
Начать новую тему Ответить на тему    Список форумов dkws.org.ua -> PHP Часовой пояс: GMT
Страница 1 из 1
 Главная страница сайта
 
Перейти:  
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
© Колисниченко Денис