I wanna something like "IN CLAUSE" in MYSQL using by magento2 ORM, something like this:

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

but by using collection in magento 2? for example something like this:


is any one have any idea?


Try below code:

$this->getCollection()->addFieldToFilter('entity_id', array(
                                        'in' => array(3,8,9,207))

Yeah you can do the following:

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

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)"));
  namespace Mageplaza\HelloWorld\Block;
 class HelloWorld extends \Magento\Framework\View\Element\Template
    protected $_productCollectionFactory;
    public function __construct(
       \Magento\Backend\Block\Template\Context $context,        
    array $data = []
       $this->_productCollectionFactory = $productCollectionFactory;    
        parent::__construct($context, $data);

// getproductcollection

public function getProductCollection()
 $collection = $this->_productCollectionFactory->create();
 $collection->addFieldToFilter('entity_id', ['in' => $Ids]);
 return $collection;
  • $collection->addAttributeToSelect('*') semicolon is missing – Msquare Feb 4 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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