To sort by an attribute for a product you'll need to edit your graphql schema.
Edit etc/schema.graphqls and copy the "products" query, or create your own query like this, by adding your own type for sorting, in the sort
column, in this case SortBySortAttributeInput
type Query {
my_custom_products_query (
search: String @doc(description: "Performs a full-text search using the specified key words."),
filter: ProductAttributeFilterInput @doc(description: "Identifies which product attributes to search for and return."),
pageSize: Int = 20 @doc(description: "Specifies the maximum number of results to return at once. This attribute is optional."),
currentPage: Int = 1 @doc(description: "Specifies which page of results to return. The default value is 1."),
sort: SortBySortAttributeInput @doc(description: "Specifies which attributes to sort on, and whether to return the results in ascending or descending order.")
): Products
@resolver(class: "Magento\\CatalogGraphQl\\Model\\Resolver\\Products") @doc(description: "The products query searches for products that match the criteria specified in the search and filter attributes.") @cache(cacheIdentity: "Magento\\CatalogGraphQl\\Model\\Resolver\\Product\\Identity")
}
Then under that in etc/schema.graphqls add the SortBySortAttributeInput
type
input SortBySortAttributeInput {
my_sort_column: SortEnum
}
Add in this input type all the attributes from a product you might wish to use for sorting your results, and give them SortEnum as input type that's accepted.
Then in your graphql query add the sorting you wish, on the columns in a Product that correspond to the columns you defined in SortBySortAttributeInput.
my_custom_products_query (
sort: {my_sort_column: ASC}
) {
items {
sort
sku
id
name
...
...
To recap: In your graphql schema's defined SortBySortAttributeInput
you define all the attributes in a product you might wish to sort on. name, id, sort_order, my_special_attribute, etc...
As type for the input you define SortEnum.
This resolves in your graphql query to:
sort: { product_column_name_defined_in_SortBySortAttributeInput: ASC | DESC }
Please note that ASC and DESC need to be written in uppercase. Graphql will return an error message saying that it couldn't find asc in SortEnum, did you mean ASC.