:::: MENU ::::
Posts tagged with: product collection

Magento 2 addAttributeToFilter

Today we discuss Magento 2 addAttributeToFilter. addAttributeToFilter is a method that can be called on EAV collections in Magento 2. That will be use in product collection, category collection, order collection customer collection and other collection too. addAttributeToFilter is adding WHERE condition in Mysql question to get collection.

addAttributeToFilter condition

There are many condition you can use with addAttributeToFilter. Example of condition equal, not equal, like , not like, in, not in, null, not null, greater than , less than , greater than equal to and less than equal to.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      return   $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addAttributeToFilter('sku’,’test’);
     
     }

Equal: eq

Now we use equal to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('status', array('eq' => 1)); // Using the operator
$this->_productCollectionFactory->addAttributeToFilter('status', 1); // Without using the operator

Not Equals – neq

Now we use not equal to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('sku', array('neq' => 'test-product'));

Like – like

Now we use Like to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('sku', array('like' => 'UX%'));

Not Like – nlike

Now we use not like to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));

In – in

Now we use In to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('in' => array(1,4,98)));

Not In – nin

Now we use not In to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('nin' => array(1,4,98)));

NULL – null

Now we use null to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('description', array('null' => true));

Not NULL – notnull

Now we use not null to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('description', array('notnull' => true));

Greater Than – gt

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('gt' => 5));

Less Than – lt

Now we use less than to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('lt' => 5));

Greater Than or Equals To- gteq

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('gteq' => 5));

Less Than or Equals To – lteq

Now we use less than equal to filter production collection.

$this->_productCollectionFactory->addAttributeToFilter('entity_id', array('lteq' => 5));
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 30, 2018


Magento 2 addFieldToFilter

Today we discuss Magento 2 addFieldToFilter. addFieldToFilter is a method that can be use to filter collections in Magento 2. That will be use in product collection, category collection, order collection customer collection and other collection too. addFieldToFilter is adding WHERE condition in Mysql question to get collection.

addFieldToFilter condition

There are many condition you can use with addFieldToFilter. Example of condition equal, not equal, like , not like, in, not in, null, not null, greater than , less than , greater than equal to and less than equal to.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      return   $this->_productCollectionFactory->create()->addAttributeToSelect('*')->addFieldToFilter('sku’,'test');
     
     }

Equal: eq

Now we use equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('status', array('eq' => 1)); // Using the operator
$this->_productCollectionFactory->addFieldToFilter('status', 1); // Without using the operator

Not Equals – neq

Now we use not equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('neq' => 'test-product'));

Like – like

Now we use Like to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('like' => 'UX%'));

Not Like – nlike

Now we use not like to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('sku', array('nlike' => 'err-prod%'));

In – in

Now we use In to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('in' => array(1,4,98)));

Not In – nin

Now we use not In to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('nin' => array(1,4,98)));

NULL – null

Now we use null to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('description', array('null' => true));

Not NULL – notnull

Now we use not null to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('description', array('notnull' => true));

Greater Than – gt

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('gt' => 5));

Less Than – lt

Now we use less than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('lt' => 5));

Greater Than or Equals To- gteq

Now we use greater than to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('gteq' => 5));

Less Than or Equals To – lteq

Now we use less than equal to filter production collection.

$this->_productCollectionFactory->addFieldToFilter('entity_id', array('lteq' => 5));
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 30, 2018


Magento 2 create product programmatically

Today we discussed how in Magento 2 create product programmatically. This tutorial includes the process of creating a simple product, set image to product and set quantity to product. So lets start with creating a simple product. We can do this in two ways- one is creating product with factory method and other is creating product with object manager.

Create Product with Factory Method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function createProduct()
    {
       
        $_product = $this->_productloader->create();
        $_product->setName('First Test Product');
        $_product->setTypeId('simple');
        $_product->setAttributeSetId(4);
        $_product->setSku('test-SKU');
        $_product->setWebsiteIds(array(1));
        $_product->setVisibility(4);
        $_product->setPrice(400);
        $_product->setImage('/simpeproduct/test.jpg');
        $_product->setSmallImage('/simpeproduct/test.jpg');
        $_product->setThumbnail('/simpeproduct/test.jpg');
        $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

        $_product->save();
        echo $_product->getId();
    }

Update Product with factory method

  protected $_product;  


  public function __construct(
     
        \Magento\Catalog\Model\ProductFactory $_product

    ) {


        $this->_productloader = $_productloader;
     
    }
    public function updateProduct()
    {
       
        $_product = $this->_productloader->create()->load(2047);
        $_product->setName('First Test Product Updated');
        $_product->save();
    }

Create Product with Object manager

 <?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $_product = $objectManager->create('Magento\Catalog\Model\Product');
    $_product->setName('First Test Product');
    $_product->setTypeId('simple');
    $_product->setAttributeSetId(4);
    $_product->setSku('test-SKU');
    $_product->setWebsiteIds(array(1));
    $_product->setVisibility(4);
    $_product->setPrice(400);
    $_product->setImage('/simpeproduct/test.jpg');
    $_product->setSmallImage('/simpeproduct/test.jpg');
    $_product->setThumbnail('/simpeproduct/test.jpg');
    $_product->setStockData(array(
            'use_config_manage_stock' => 0, //'Use config settings' checkbox
            'manage_stock' => 1, //manage stock
            'min_sale_qty' => 1, //Minimum Qty Allowed in Shopping Cart
            'max_sale_qty' => 2, //Maximum Qty Allowed in Shopping Cart
            'is_in_stock' => 1, //Stock Availability
            'qty' => 1000 //qty
            )
        );

$_product->save();
echo $_product->getId();

Update Product with Object manager

Now our custom product is created. Now we will update product. So doing with following example just.

            $_product = $objectManager->create('Magento\Catalog\Model\Product')->load(2047);
    $_product->setName('First Test Product Updated');
    $_product->save(); ?>
Author: Qaisar Satti
Category: Magento 2
Last Modified: August 2, 2018


Magento 2 sort collection by given ids

Today we discuss how in Magento 2 sort collection by give ids. Sometime we need to get product collection by given ids form example random ids 5,4,13. We take the example of product collection and filter it by give ids. You can use this on any kind of collection like order collection, category collection and any custom collection too. So here is our example.

protected $_productCollectionFactory;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
         $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
        $productIds=array(9,21,5,3);
        $productCollection = $this->_productCollectionFactory->create();
        $productCollection->getSelect()->order(new \Zend_Db_Expr('FIELD(entity_id,' . implode(',', $productIds).')'));
        return $productCollection;
     
     }

Note: You can sort any collection following this example.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 join multiple tables

Today we talk about how in Magento 2 join multiple tables. Sometime you need to get join collection with product collection data or category collection data or order collection or custom table collection. So today we focus on how to join two magento 2. Then we talk about multiple table join. Now taking a example of we need to join product collection with custom table. Here we go.

protected $_productCollectionFactory;  


      public function __construct(

            \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory

        ) {


            $this->_productloader = $_productCollectionFactory;

        }

    public getmyCollection(){
    $collection = $this->productCollectionFactory->create();
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['column1'=>'table1join.column1','column2'=>'table1join.column2']);
    return $collection;
    }

Now we try the example of multiple table join

public getmyCollection(){
    $collection = $this->productCollectionFactory->create();
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['column1'=>'table1join.column1','column2'=>'table1join.column2']);
    $collection->getSelect()->join(
                ['table1join'=>$collection->getTable('table1join')],
                'main_table.entity_id = table1join.product_id',
                ['table2column1'=>'table1join.column1','table2column1'=>'table1join.column2']);
       $collection->getSelect()->join(
            ['table2join'=>$collection->getTable('table2join')],
            'main_table.entity_id = table2join.product_id',
            ['table3column1'=>'table2join.column1','table3column1'=>'table2join.column2']);
      return $collection;
    }

You can use same example to join in any collection in magento 2.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 most viewed product collection

Let’s talk about using report collection so today we talk about how to get Magento 2 most viewed product collection. Most viewed production collection in depend on number of time product viewed by user. First we have to inject the Reports\ProductCollection in you block or helper any other file you want to use it. So let start with coding. In this example I am going to inject into my block.

Step 1: Create a block file

<?php
  /**
  * Simple Hello World Module
  *
  * @category QaisarSatti
  * @package  QaisarSatti_HelloWorld
  * @author   Muhammad Qaisar Satti
  * @Email    [email protected]
  *
  */

namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{
 
  protected $_collectionFactory;
  protected $_productsFactory;
   public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Reports\Model\ResourceModel\Product\CollectionFactory $productsFactory,
    array $data = []
   ) {
 
        $this->_productsFactory = $productsFactory;
    parent::__construct($context, $data);
   }
public function getMostViewedData(){
   
    $mostViewedCollection = $this->_productsFactory->create()->addViewsCount();  
    return $mostViewedCollection;
   }
}

Step 2: Show Output

Getting collection in phtml file from block.

<!--/**
  * Simple Hello World Module
  *
  * @category QaisarSatti
  * @package  QaisarSatti_HelloWorld
  * @author   Muhammad Qaisar Satti
  * @Email    [email protected]
  *
  */
-->
  <?php
      $mostViewedProduct =  $block->getMostViewedData(); ?>
      <h1>Most Viewed Collection.....</h1>
      <ul>
          <?php foreach ($mostViewedProduct as $viewedProduct) {
              ?>
              <li><?php echo $viewedProduct>getSku();?>--<?php echo $viewedProduct>getViews();?></li>
          <?php } ?>
</ul>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Magento 2 best Seller product collection

Let’s talk about using sales report collection so today we talk about how to get Magento 2 best seller product collection. Best seller collection in depend on number of time product quantity is sold. First we have to inject the Bestsellers\CollectionFactory in you block or helper any other file you want to use it. You can get the report of monthly,yearly and daily and also custom date. So let start with coding. In this example I am going to inject into my block.

Step 1: Create a block file

<?php
    /**
    * Simple Hello World Module
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
    */

namespace QaisarSatti\HelloWorld\Block;
class BestSeller extends \Magento\Framework\View\Element\Template
{
 
    protected $_collectionFactory;
   public function __construct(
       \Magento\Backend\Block\Template\Context $context,
      \Magento\Sales\Model\ResourceModel\Report\Bestsellers\CollectionFactory $collectionFactory,
               array $data = []
   ) {
 
       $this->_collectionFactory = $collectionFactory;
             parent::__construct($context, $data);
   }


public function getBestSellerData(){
     
$bestSellerProdcutCollection = $this->_collectionFactory->create()
                    ->setModel('Magento\Catalog\Model\Product')
                    ->setPeriod('month') //you can add period daily,yearly
                   ;
           
       return $bestSellerProdcutCollection;
   }
}

Step 2: Show Output

Getting collection in phtml file from block.

<!--/**
    * Simple Hello World Module
    *
    * @category    QaisarSatti
    * @package     QaisarSatti_HelloWorld
    * @author      Muhammad Qaisar Satti
    * @Email       [email protected]
    *
    */
-->

    <?php
        $bestSeller =  $block->getBestSellerData(); ?>
        <h1>Best Seller Collection.....</h1>
        <ul>
            <?php foreach ($bestSeller as $product) {
                ?>
                <li><?php  echo $product->getProductName();?>--<?php  echo $product->getQtyOrdered();?></li>
            <?php } ?>
</ul>
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


Pages:12