1

I am sorting a custom collection by a text field EAV attribute (UMC was originally used to scaffold the module which has been heavily modified since).

$myCollection->setOrder('my_name', 'ASC')

my_name in this case often has the same value for many entries. Consider a collection of dogs. Many entries would have labrador as a value for breed field. There are many possible fields so keeping them enumerated in a <select> list would be cumbersome, I'd rather keep them as a text field (with my own validation so that labrador isn't mistaken as labredor or something).

The problem is that my returned results will randomly order the my_name field so that any entries with the same value will be clustered together but will be listed in a different order every time. How can I make sure this ordered collection is the same each time?

  • Just to add a note: I am able to work around the issue by also sorting by an additional unique field that is related to the other field but insufficient to sort by alone. – pspahn Jan 19 '18 at 19:20
1

Based on your comment, why not sort by both, breed and that second (or any other) attribute? :)

i.e.

$products = Mage::getModel('catalog/product')->getCollection()
    ->addAttributeToSelect('breed','other_field');

$products->getSelect()
    ->order(new Zend_Db_Expr('e.breed asc, e.other_field desc'));

foreach($products as $product) {
    var_dump($product->getData());
}

This will build a query similar to

SELECT `e`.`entity_id`, `e`.`type_id`, `e`.`attribute_set_id`, `e`.`breed`, `e`.`other_field` FROM `catalog_product_flat_1` AS `e` WHERE (e.status = 1) ORDER BY `e`.`breed` asc, `e`.`other_field` asc

which sorts first by breed and then by other_field.

|improve this answer|||||
  • Yes, in my case I realized I could sort by an additional field, but that may not necessarily be the case. – pspahn Jan 19 '18 at 22:52
  • 1
    @pspahn you can always additionally sort by id/entity_id in case you don't have other attributes available. This way your sorting should stay the same anyway. – Christoph Farnleitner Jan 19 '18 at 23:03
  • Ah yes, of course. In my specific case it is just a touch cleaner to sort by my other field, but sorting by ID seems like a good work around for most cases. – pspahn Jan 20 '18 at 3:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.