Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only specific fields in Magento

I'm trying to use the MAX function of MySQL to retrieve the latest dates from my table.

$_updates = Mage::getModel('ticket/updates')->getCollection();  
$_updates->getSelect()->columns('MAX(created) as max_created')->group(array('status_id'));

This is the resulting query:

SELECT `main_table`.*, MAX(created) AS `max_created` FROM `em_ticket_updates` AS `main_table` GROUP BY `status_id` 

The problem with this is that if all the fields are included (main_table.*) it does not function correctly.

Is there a way to remove main_table.* from the query and only use specific fields?

Thanks.

like image 958
Jjj Avatar asked Dec 08 '11 15:12

Jjj


3 Answers

A Zend trick can be used here.

$_updates->getSelect()
    ->reset(Zend_Db_Select::COLUMNS)
    ->columns('MAX(created) as max_created')
    ->group(array('status_id'));

NOTE:

For EAV collection you must re-add the entity_id or you will have an error when the collection is loaded.

    $collection = Mage::getModel('catalog/product')
        ->getCollection();
    $collection->getSelect()
        ->reset(Zend_Db_Select::COLUMNS)
        ->columns(array('entity_id')); 

    $collection
        ->addAttributeToSelect(array('image','small_image','thumbnail'))
        ->addFieldToFilter('entity_id', array('in' => $simple_ids));
like image 126
clockworkgeek Avatar answered Oct 28 '22 02:10

clockworkgeek


Magento provide addFieldToSelect() fumctionality. Use below code to get specific field.

$Collection = Mage::getModel('showdown/votes')->getCollection();
$Collection->addFieldToSelect('id');
like image 7
Neeraj Garg Avatar answered Oct 28 '22 02:10

Neeraj Garg


I recognise this is an old post but I thought I'd post an alternative solution.

I had a similar problem myself, I eventually searched through the source until I reached Zend_Db_Select After consulting the Zend Documentation (Example 8).

$select = $db->select()
    ->from(array('p' => 'products'),
           array('product_id', 'product_name'));
like image 5
Ash Avatar answered Oct 28 '22 03:10

Ash