Nested items in Ecto, sorting

I have Category and it has many articles. I want to load a Category from a db and sort Articles in it based on “inserted_at” date of an Article.

    ctg = Repo.get(Category, 123)
    |> Repo.preload([article: :mmedia_entity])

    # how? ????
    # |> order_by(asc: :article.inserted_at)

How to do that?

Maybe

import Ecto.Query

ctg =
  Category 
  |> Repo.get(123)
  |> Repo.preload([articles: {from(a in Article, order_by: a.inserted_at), :mmedia_entity}]

See more examples at https://hexdocs.pm/ecto/Ecto.Repo.html#c:preload/3.

3 Likes