Yanick Schraner
Yanick Schraner

Reputation: 315

magento filter order by product id and customer id

How can I get all magento orders ordered by a specific customer containing a specific product? I tried the following:

        $customer_id = Mage::getSingleton('customer/session')->getCustomerId();
        $customer_eamil = Mage::getSingleton('customer/session')->getCustomerEmail();


        $event = $observer->getEvent();
        $product = $event->getProduct();
        $product->original_price = $product->getPrice();
        $productID = $product->getId();

        $fromDate = date('Y-m-d H:i:s', strtotime(date('Y-01-01')));
        $toDate = date('Y-m-d H:i:s');

        $orders = Mage::getResourceModel('sales/order_item_collection')
            ->addFieldToSelect('*')
            ->addAttributeToFilter('created_at', array('from'=>$fromDate, 'to'=>$toDate))
            ->addAttributeToFilter('product_id', array('eq' => $productID))
            ->addAttributeToFilter('customer_id', $customer_id)
        ;

But all I get is an error in my magento error.log: exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_id' in 'where clause''

I am using magent 1.9.2

Thank you for your help.

Upvotes: 0

Views: 1688

Answers (1)

Nits
Nits

Reputation: 111

Please check below code to get desire result:

$customer_id = Mage::getSingleton('customer/session')->getCustomerId();
$customer_eamil = Mage::getSingleton('customer/session')->getCustomerEmail();

$event = $observer->getEvent();
$product = $event->getProduct();
$product->original_price = $product->getPrice();
$productID = $product->getId();

$fromDate = date('Y-m-d H:i:s', strtotime(date('Y-01-01')));
$toDate = date('Y-m-d H:i:s');

$orders = Mage::getResourceModel('sales/order_item_collection')
        ->addFieldToSelect('*')
        ->addAttributeToFilter('created_at', array('from' => $fromDate, 'to' => $toDate))
        ->addAttributeToFilter('product_id', array('eq' => $productID));

$orders->getSelect()->join(array('sales_order' => Mage::getSingleton('core/resource')->getTableName('sales/order')), 'main_table.order_id = sales_order.entity_id and customer_id=' . $customer_id, array('sales_order.entity_id'));

echo "<pre>";
print_r($orders->getData());
exit; 

Please check data available using above filter in DB.

Upvotes: 1

Related Questions