Question

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 
Was it helpful?

Solution

Give it a try -

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

OTHER TIPS

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); 
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top