简体   繁体   中英

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.

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));

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

$Collection = Mage::getModel('showdown/votes')->getCollection();
$Collection->addFieldToSelect('id');

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'));

Just need to use " getColumnValues "

$_updates = Mage::getModel('ticket/updates')->getCollection(); 
$columnValues = $_updates->getColumnValues('Your Column Name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM