13

I want something like the "IN CLAUSE" in MYSQL via magento2 ORM, for example:

select * from product where id in (...)

but by using getCollection in magento 2 to get something like this:

$this->getCollection()->addFieldToFilter('id','in',[...]);

How can I achieve this?

4 Answers 4

10

Try below code:

$this->getCollection()->addFieldToFilter('entity_id', array(
                                        'in' => array(3,8,9,207))
                                        );
7
  <?php
  namespace Mageplaza\HelloWorld\Block;
 class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;
    public function __construct(
       \Magento\Backend\Block\Template\Context $context,        
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory 
        $productCollectionFactory,        
    array $data = []
)
{    
       $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);
}

// getproductcollection

public function getProductCollection()
{
 Ids=array(1,2,3);
 $collection = $this->_productCollectionFactory->create();
 $collection->addAttributeToSelect('*');   //semicolon is missing                  
 $collection->addFieldToFilter('entity_id', ['in' => $Ids]);
 return $collection;
}
}
?>
1
  • 1
    $collection->addAttributeToSelect('*') semicolon is missing
    – Msquare
    Commented Feb 4, 2020 at 14:34
6

Yeah you can do the following:

$this->getCollection()->addFieldToFilter('entity_id',['in' => [...]]);
1
  • what is the difference between using filter with 'entity_id' & 'id' ?
    – Sarvagya
    Commented Feb 13, 2019 at 12:42
3

If you want get the collection which keep its ids order that is not ASC or DESC, you could use codes like below:

$ids = '4,5,3,1,2';
$collection = $this->collectionFactory->create()
        ->addFieldToFilter('id', ['in' => $ids])
$collection->getSelect()->order(new \Zend_Db_Expr("FIELD(entity_id,$ids)"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.