Show Menu
Cheatography

Magento 2 Product Collection Cheat Sheet by

Magento 2 Product Collection usefuls

Import statement

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory as ProductCollectionFactory;

Constr­uctor

/**
 * @var ProductCollectionFactory
 */
private $productCollectionFactory;

/**
 * @param ProductCollectionFactory $productCollectionFactory
 */
public function __construct(
    ProductCollectionFactory $productCollectionFactory
) {
    $this->productCollectionFactory = $productCollectionFactory;
}

Product Types

\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE
\Magento\Catalog\Model\Product\Type::TYPE_BUNDLE
\Magento\Catalog\Model\Product\Type::TYPE_VIRTUAL
\Magento\Downloadable\Model\Product\Type::TYPE_DOWNLOADABLE
\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE
\Magento\GroupedProduct\Model\Product\Type\Grouped::TYPE_CODE

Visibility filter

/**
 * @var \Magento\Catalog\Model\Product\Visibility
 */
protected $productVisibility;

public function __construct(
    \Magento\Catalog\Model\Product\Visibility $productVisibility,
) {
    $this->productVisibility = $productVisibility;
}

[...]
$collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
[...]

Filters

// Is Equal To
$collection->addAttributeToFilter('status', ['eq' => 1]);

// Is Not Equal To
$collection->addAttributeToFilter('visibility', ['neq' => 1]);

// Greater Than
$collection->addAttributeToFilter('price', ['gt' => 3]);

// Less Than
$collection->addAttributeToFilter('price', ['lt' => 3]);

// Greater Than or Equal To
$collection->addAttributeToFilter('price', ['gteq' => 4]);

// Less Than or Equal To
$collection->addAttributeToFilter('price', ['lteq' => 4]);

// Contains – with % wildcards
$collection->addAttributeToFilter('sku', ['like' => 'DVD%']);

// Does Not Contain – with % wildcards
$collection->addAttributeToFilter('sku', ['nlike' => 'ABC%']);

// In Array
$collection->addAttributeToFilter('entity_id', ['in' => [1,3,12]]);

// Not In Array
$collection->addAttributeToFilter('entity_id', ['nin' => [1,2,12]]);

// Is NULL
$collection->addAttributeToFilter('description', 'null');
$collection->addAttributeToFilter('description', ['null' => true]);

// Is Not NULL
$collection->addAttributeToFilter('description', 'notnull');
$collection->addAttributeToFilter('description', ['notnull' => true]);

Add Price Data

$collection->addPriceData();

Simple filter

$collection->addAttributeToFilter('type_id', $typeFilter);

More complex filter

$collection->addAttributeToFilter(
    'status',
    ['in' => 'processing']
);

Or filter

// Or
$collection->addAttributeToFilter([
    [
        'attribute' => 'download_link',
        'null' => true,
    ],
    [
        'attribute' => 'download_link',
        'eq' => '',
    ],
]);

In Stock Filter

/**
 * @var \Magento\CatalogInventory\Helper\Stock
 */
protected $stockHelper;

 public function __construct(
     \Magento\CatalogInventory\Helper\Stock $stockHelper
) {
     $this->stockHelper = $stockHelper;
}

[...]
$this->stockFilter->addInStockFilterToCollection($collection);
[...]

Get Price Data

$collection->getMaxPrice();
$collection->getMinPrice();
$collection->getPriceStandardDeviation();
$collection->getPricesCount();
 

Create

$collection = $this->productCollectionFactory->create();

Filter by Product ID

$collection->addIdFilter($productId);

Filter by Store ID

$collection->addStoreFilter($storeId);

Select Attribute

$collection->addAttributeToSelect($attributeCode);

Get first item

return $collection->getFirstItem();

Get raw attribute value

return $collection->getFirstItem()->getData($attributeCode);

Status Filter

/**
 * @var Magento\Catalog\Model\Product\Attribute\Source\Status
 */
protected $productStatus;

public function __construct(
    \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus
) {
    $this->productStatus = $productStatus;
}

[...]
$collection->addAttributeToFilter(
    'status',
    ['in' => $this->productStatus->getVisibleStatusIds()
]);
[...]

Category Filter

$collection->addCategoryFilter($category);

Return only IDs

return $collection->getAllIds();

Debug Query

echo (string) $collection->getSelect();
$collection->printLogQuery(true);

Add Media

$collection->addMediaGalleryData();

Add Tier Price Data

$collection->addTierPriceData();
$collection->addTierPriceDataByGroupId($customerGroupId);

Add Category IDs

$collection->addCategoryIds();

Add Website Names

$collection->addWebsiteNamesToResult();

Join Stock Qty to collection

$collection->joinField(
    'qty',
    'cataloginventory_stock_item',
    'qty',
    'product_id=entity_id',
    '{{table}}.stock_id=1',
    'left'
);

Generic Collection

// Sort Collection
// Order by Attribute Ascending
$collection->setOrder('price', 'ASC');
 
// Order by Attribute Descending
$collection->setOrder('name', 'DESC');

// Random Order
$collection->setOrder('rand()');

// Limit Collection
$collection->setPageSize(10);
$collection->setCurPage(1);
 
// Count Results
$collection->count();

Add URL data

$collection->addUrlRewrite($categoryId);

Add Tax Percents

$collection->addTaxPercents();

Add Options

$collection->addOptionsToResult();

Add Sort

$collection->addAttributeToSort('name', 'DESC');

Free Up Memory

$collection->clear();

Help Us Go Positive!

We offset our carbon usage with Ecologi. Click the link below to help us!

We offset our carbon footprint via Ecologi
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Rare Book Abbreviations Cheat Sheet
          Magento 2 Cheat Sheet

          More Cheat Sheets by DominicXigen