I need to sort a collection by an attribute, taking into account only the numbers and decimal places of this attribute, ignoring the letters. I don't think there is anyway to use addAttributeToSort here. On version Magento 2.3.

The collection is of catalog_product_entity. The attribute I need to sort by is in catalog_product_entity_text. The collection is filtered by another attribute already, no further filtering needed, just sort.

The attribute and value are in catalog_product_entity_text; let's call the attribute test_group and it can have values similar to this: CA350, AB100, B225, BB100.5 etc..

How can I sort the collection so I end up with the collection in the order of AB100, BB100.5, B225, CA350?

I've tried $collection->getItems(), sort these items, delete items in collection, push these sorted items to collection. This results in very slow performance, so I would like to utilize mysql to handle the sorting, like addAttributeToSort does. I also do not want to overwrite the existing attribute in the collection.

I'm still learning mysql and haven't had any success with my attempts, but I'm thinking something like


but with the test_group_no_char not containing letters.

1 Answer 1


You can try something like below

$giftColletion = $this->_giftFactory->getCollection();
$giftColletion->addFieldToFilter('store_id', 1);

setOrder is use for sorting

  • Thanks for looking, but I have to sort the attribute using only the numbers (ignoring the letters). The attribute will contain a combination of both such as: AB100. It needs to sort just using the 100 part of the attribute. Using setOrder doesn't work for this.
    – morrigan
    Feb 15, 2022 at 20:10
  • I don't know any solution for what you are looking for. Even I don't think it's possible Feb 16, 2022 at 4:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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