Note: I am using MySQL 5.7.
I have two tables named Post, Comment
schema "posts" do
field: id, string
field :title, :string
field :slug, :string
field :active, :boolean, default: true
timestamps()
end
schema "comments" do
field: id, string
field: post_id, string
field :title, :string
field :body, :string
field :email, :string
field :meta, :map
field :active, :boolean, default: false
timestamps()
end
I am using Ecto for the database queries in Elixir. Currently, I am having the issue of trying to get all the posts in the database, and the most recent comment for those posts, if available. E.g:
Post 1 ──── post1__last_comment_id
Post 2 ──── post2__last_comment_id
Post 3 ──── nil
I have tried join_left on post.id == comment.id, but that returns all the comments related to the post not just the most recent one.
I tried also grouping_by comment.post_id and get the max id, while that worked, that is not the desired solution as there is a requirement for it to be based on date rather than id of the comment.
I looked up how to do it, while I found few solutions for raw SQL queries, I could not find any similar things for Ecto, and could not figure out how to convert it from SQL to Ecto.
Is it possible to be done using Ecto?