3

I am using below code but it is giving error please help.

$collection = Mage::getModel("sales/order_invoice")->getCollection()->addFieldToFilter('customer_id',$customerId);

2 Answers 2

5

Magento did not save Customer id on Sales_flat_Invoice table so If you want to filter the invoice Collection using customer id and you need to MySQL join with Sales_flat_order table

Step1: Get Invoice resource Collection

  $collection= Mage::getResourceModel('sales/order_invoice_collection');

Step2: add sales_flat_order table to collection.In magento, sales_flat_order and sales_flat_invoice table related with Invoice table order_id and sales_flat_order table entity_id

$select = $collection->getSelect();
$select->joinLeft(array('order' => Mage::getModel('core/resource')->getTableName('sales/order')), 'order.entity_id=main_table.order_id', array('customer_id' => 'customer_id'))

Now You can filter invoice collection by customer id

$collection->addFieldToFilter('customer_id',$customerId)
5
  • Have you tried running this code live? 'Can't retrieve entity config: sales/flat_order' is the error I receive when trying to do so.
    – Moose
    Commented Jan 9, 2015 at 7:23
  • check now.... Can please tell me,Is your system file have table prefix
    – Amit Bera
    Commented Jan 9, 2015 at 7:27
  • 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'main_table.Id' - and no, I don't have table prefixes.
    – Moose
    Commented Jan 9, 2015 at 7:30
  • please check now
    – Amit Bera
    Commented Jan 9, 2015 at 7:39
  • Looks to work now, third time's a charm. ;-)
    – Moose
    Commented Jan 9, 2015 at 7:42
0

Magento does not store the customer_id column in sales_flat_invoice which is where the collection is found. It does however store the order_id field, so the following approach works 100%:

$orders = Mage::getModel("sales/order")->getCollection()->addFieldToFilter('customer_id',$customer_id);
$order_ids = array();
foreach ($orders as $order){
    array_push($order_ids,$order->getId());
}
$collection = Mage::getModel("sales/order_invoice")->getCollection()->addFieldToFilter('order_id',array('in'=>$order_ids));
  • The first four lines of code assemble the order_id which belong to the customer.
  • The fifth line simply filters the invoice collection by those order_id values.

Voila!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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