Using Magento's addFieldToFilter to filter by existing columns


Hypothetical situation. I want to populate/load a sales/order collection with every order where the grand_total is equal to the total_paid. I know I can use addFieldToFilter to filter by a specific value, but is it possible to use this method to filter by other database values. If not, is there any data access object in the Magento system that allows this.

$orders = Mage::getModel('sales/order');
$orders = $orders->getCollection();
$orders->addFieldToFilter('total_paid',Array('eq'=>30));  //would find all the orders that were 30 
//syntax to find all the orders whose total_paid value is equal to it's grand_total attribute

The non-eav SQL concept I’m grasping for is:

SELECT * FROM Orders o WHERE o.total_paid = o.grand_total

Is this possible to do purely with object method calls, or do I need to do post-load filtering?

How do other ORM systems handle this?

7/5/2014 2:01:10 PM

Accepted Answer

I was waiting for a definite answer to this, but seeing as nothing's come up I might as well share what I've found out. I traced addFieldToFilter and apparently every value you use ends up quoted so you can't really "hack" this by using the name of a column. In fact I don't see any way to do this, at least not within this class.

Realistically I think you'll need to go with post-load filtering, at least for now. This of course is the very definition of inefficient code, but then again if computational efficiency was a priority, you wouldn't be using Magento in the first place...

3/19/2009 12:03:06 PM

Just had to address this in one of my projects and came across this question while searching for a better resolution. My hack looks like this:

$orders = Mage::getModel('sales/order')->getCollection();

It annoys me that such a basic functionality of databases is overlooked by Magento's ORM.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow