简体   繁体   中英

Sort order by multiple fields Magento Custom collection

here is my table structure:

+----+---------------------+
| id | event_date          |
+----+---------------------+
| 12 | 2017-07-03 01:12:00 |
| 42 | 2017-07-04 18:13:00 |
| 52 | 2017-07-22 23:52:00 |
| 62 | 2017-10-20 23:55:00 |
+----+---------------------+
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| name       | varchar(255) | YES  |     | NULL    |                |
| status     | tinyint(2)   | NO   |     | 0       |                |
| content    | text         | NO   |     | NULL    |                |
| event_date | datetime     | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+

I want to get latest two records with date order as ascending.

Following is the code I am using :

$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
        ->addFieldToFilter('status', 0)
        ->setOrder('id', 'DESC')
        ->setOrder('event_date', 'ASC')
        ->setPageSize(2);

It is giving records using ID. I want to sort by using both fields. Although, when I tried to sort using only date, it worked fine.

You could use addAttributeToSort()

$collection = Mage::getModel("blogpromo/blogpromo")->getCollection()
    ->addFieldToFilter('status', 0)
    ->addAttributeToSort('id', 'DESC')
    ->addAttributeToSort('event_date', 'ASC')
    ->setPageSize(2);

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