AD0-E717 practice question 9 of 15

Which two methods add sorting to collections inherited from the \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection class? (Choose two.)

Full set: 77 questions
Answer options
A: setOrder Correct answer
B: setSorting
C: addSorting
D: addOrder Correct answer
Correct Answer:
A. setOrder; D. addOrder
Explanation

The \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection class inherits its sorting capabilities from \Magento\Framework\Data\Collection\AbstractDb. This parent class provides two primary methods for applying SQL ORDER BY clauses. The addOrder($field, $direction) method appends a new sorting condition to the collection's query, allowing for multi-field sorting. The setOrder($field, $direction) method clears any previously set sorting conditions and applies a new one. Both are valid ways to sort a collection.

Why Incorrect

B. setSorting: This method does not exist in the \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection class or its parent classes for the purpose of sorting database query results.
C. addSorting: This is not a valid method within the Magento Framework's collection class hierarchy for adding a sort order to a database query.

References

1. Adobe Commerce Developer Documentation, Database collections: "To sort the collection, call the addOrder method on the collection object. The first argument is the field to sort on. The second argument is the direction of the sort."

Source: Adobe Commerce Developer Guide > PHP Developer Guide > Data objects > Database collections > Filter and sort the collection.

2. Magento Framework Source Code, AbstractDb.php: The class \Magento\Framework\Data\Collection\AbstractDb, which is a parent of AbstractCollection, defines both methods.

public function addOrder($field, $direction = self::SORTORDERDESC)

public function setOrder($field, $direction = self::SORTORDERDESC)

Source: vendor/magento/framework/Data/Collection/AbstractDb.php, Lines 467-496 (in Magento 2.4.x).

Scroll to Top