3

I get categories collection from product object. I have to pick category with lowest level possible. To achieve this I want to sort collection by level and take first item. Although any method I know doesn't work. I have tried:

  • setOrder()
  • addAttributeToSort()
  • getSelect()->order()

Why is it like this and is there any way to achieve it? Of course I can use getData() and than work with array but it doesn't seem to be good solution.

2

This is because the collection has probably already been loaded. I'm not sure which place specifically you're grabbing the product from, as different attributes are loaded in different places, but more than likely, the collection has been loaded, and therefore the sorting changes (which all boil down to the SQL query) aren't taken into account.

A possible solution would be to reload the collection ($collection->load() should do the trick), but that's not the most performant method. I suggest attempting to observe an event or declare a plugin that will modify the collection query before it is run.

  • Actually it has impact! Maybe because in my class I was using the same collection in different places. There could have been conflict between loading/filtering/sorting collection methods. – Bartosz Kubicki Dec 29 '16 at 10:14

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.