Group pages by field, then sort alphabetically by text on that field

Ok, so I group my $products by their $product->artist() field, using groupBy, all good:

$artists = $products->groupBy('artist');

If I understand it right I get a collection (A) where each entry has $product->artist() as key, then a collection (B) of the grouped pages under that artist.

$products (collection A) (
  'artist name' => pages object (collection B)
  ...
)

Now I’d like to sort $products, (collection A), alphabetically by the artist’s names.

As far as I understand, collection->sortBy() expects me to pass a field, but that does not match my use case. I suppose I need to use sort() directly, but how ?

Thank you

What does the artist field contain`? Not the name of the artist?

Yes that is what it contains, but I want to sort the groups, not each individual page, and in each group, the artist name is a key for that collection, not a field, right ?

But if you sort the collection by the artist name, the groups will automatically be sorted as well.

Sorry, but how should I sort the collection by artist name in this case?

$artists = $products->groupBy('artist');

… then ?

Because doing

$artists->sortBy('artist');

…does not work. I assume because $artists is not a $pages collection, and so there is no ‘artist’ field in each entry. There is a key and a collection per entry. And I want to sort by that key.

Danke

$artists = $products->sortBy('artist')->groupBy('artist');
1 Like

Ah, but of course. I was looking at the problem upside-down

Danke schön.