1

I have below code

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$orderRepository = $objectManager->get('\Magento\Sales\Api\OrderRepositoryInterface');
$customModel = $objectManager->get('\Custom\Module\Model\ResourceModel\Index\Collection');

$orderIdsArray = array(3123,3124);

if(count($orderIdsArray) > 0 ){
    foreach($orderIdsArray as $orderId){
        $oId = $orderRepository->get($orderId);
        if($oId->getId()){
            $items = $oId->getAllItems();
            if (count($items) > 0 && count($items) == 1) {
                foreach ($items as $item) {
                    $products = $customModel->addFieldToFilter('product_id', $item->getProductId());
                    echo $products->getSelect()->__toString().'='.count($products); 
                }
            }
        }
    }
}

First query it print

SELECT `main_table`.* FROM `custom_table` AS `main_table` WHERE (`product_id` = '2482')
SELECT `main_table`.* FROM `custom_table` AS `main_table` WHERE (`product_id` = '2482') AND (`product_id` = '1') <-- WRONG

How can i get below ones?

SELECT `main_table`.* FROM `custom_table` AS `main_table` WHERE (`product_id` = '1') <-- CORRECT 
2

Give it a try -

foreach ($items as $item) {
    $products = clone $customModel;
    $products->addFieldToFilter('product_id', $item->getProductId());
    echo $products->getSelect()->__toString().'='.count($products); 
}
0

You can try to add the following line after every time you get your products in the loop

$products->getSelect()->reset('where');

for testing add it after

echo $products->getSelect()->__toString().'='.count($products); 
  • Already tried this one. Not working :( – Ankit Shah Jun 16 '17 at 1:17
  • For me worked fine though – Nikolas Jun 16 '17 at 16:05
  • $products->clear()->getSelect()->reset('where'); Also It's worked – Karangar Meghnathi Jun 28 '18 at 7: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.