7

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:

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

is any one have any idea?

8

Try below code:

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

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 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)"));
3
  <?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('*')
 $collection->addFieldToFilter('entity_id', ['in' => $Ids]);
 return $collection;
}
}
?>

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.