I was wondering how you can select columns. Above you can see the sql I wanna write in the controller. But I want to do this the wright way. Like other sql statements in magento.
I tried to add ->columns(‘o.sku AS SKU’) but this didn’t work.
Any ideas? Thanks in advance!
//sql
$readresult="SELECT o.name AS 'Product', o.sku AS 'SKU', c.entity_id AS 'Order', c.customer_email AS 'Email', c.customer_firstname AS 'Voornaam', c.customer_lastname AS 'Achternaam', c.customer_middlename AS 'Tussenvoegsel', o.product_options AS 'Options', a.telephone AS 'Telefoon', a.postcode AS 'Postcode', a.street AS 'Street', a.city AS 'City', c.increment_id AS 'Bestelnr' FROM magento_sales_flat_order AS c INNER JOIN magento_sales_flat_order_item AS o ON c.entity_id = o.order_id INNER JOIN magento_sales_flat_order_address AS a ON a.parent_id = c.entity_id WHERE o.product_id =".$product." GROUP BY c.entity_id ORDER BY o.sku;";
//THE MAGENTO WAY!
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('core_read');
$o = $resource->getTableName('magento_sales_flat_order');
$o_item = $resource->getTableName('magento_sales_flat_order_item');
$o_address = $resource->getTableName('magento_sales_flat_order_address');
$select = $read->select()->from(array('c'=>$o))
->join(array('o'=>$o_item), 'c.entity_id = o.order_id', array(o.sku AS 'SKU'))
->join(array('a'=>$o_address), 'a.parent_id = c.entity_id', array())
->where('o.product_id', $product)
->group('c.entity_id')
->order('o.sku');
You souldn’t work like this with core modules at all. Those low level SQL queries should be used by resource models only. Especially not within a controller.
You should get an instance of
Mage_Sales_Model_Resource_Order_Collectionby callingMage::getModel('sales/order')->getCollection()and build your query from there. Just have a look at the source code to find out about how to do that exactly; start at app/code/core/Mage/Sales/Model/Resource/Order/Collection.php and work your way down the inheritance chain.For example, you can add a
WHEREusing something like$collection->addAttributeToSearchFilter().Magento’s got great database abstraction and you sould definately be using it.
Hope this helps.