sanjeevmalagi1

sanjeevmalagi1

How to create a dynamic Ecto query?

Hi,

In my project, I have tables called Posts and Comments.
I have been given the requirement that each post will have multiple comments and each comment will have a post. Also each POST will have only one active comment.

So I have a schema defined like this.
post_schema.ex

  schema "post" do
    field :title, :string
    ...
    ...
    has_many :comments, Comment

    timestamps()
  end

comment_schema.ex

schema "comment" do
    field :message, :string
    ...
    ...
    field :is_active, :boolean
    field :is_active_last_updated, :utc_datetime

    belongs_to :post, Post, type: :binary_id

    timestamps()
  end

The comment also has is_active and is_active_last_updated property.

I have a business requirement where I need to get the list of posts along with active comment. And If a POST does not have any active comments. I need to get the latest active comment indicated by is_active_last_updated .

example:
POST#1

%{
  title: "This is post 1",
  id: "uuid-uuid-uuid-uuid-1",
  comments: [
    %{
      message: "This is a post 1 message",
      id: "uuid-uuid-uuid-message-1",
      is_active: true,
      is_active_last_updated: ~U[2024-03-15 15:50:18Z]
    },
    %{
      message: "This is another post 1 message which is inactive",
      id: "uuid-uuid-uuid-message-2",
      is_active: false,
      is_active_last_updated: ~U[2024-03-15 12:50:18Z]
    },
    %{
      message: "This is another post 1 message which is inactive",
      id: "uuid-uuid-uuid-message-3",
      is_active: false,
      is_active_last_updated: ~U[2024-03-15 11:50:18Z]
    }
  ]
}

POST#2

%{
  title: "This is post 2",
  id: "uuid-uuid-uuid-uuid-2",
  comments: [
    %{
      message: "This is a post 2 message which in inactive",
      id: "uuid-uuid-uuid-message-4",
      is_active: false,
      is_active_last_updated: ~U[2024-03-15 15:50:18Z]
    },
    %{
      message: "This is another post 2 message which is inactive",
      id: "uuid-uuid-uuid-message-5",
      is_active: false,
      is_active_last_updated: ~U[2024-03-15 12:50:18Z]
    },
    %{
      message: "This is another post 2 message which is inactive",
      id: "uuid-uuid-uuid-message-6",
      is_active: false,
      is_active_last_updated: ~U[2024-03-15 11:50:18Z]
    }
  ]
}

Here I need to write a query such that I get the response of

[
  %{
    title: "This is post 1",
    id: "uuid-uuid-uuid-uuid-1",
    comments: [
      %{
        message: "This is a post 1 message",
        id: "uuid-uuid-uuid-message-1",
        is_active: true,
        is_active_last_updated: ~U[2024-03-15 15:50:18Z]
      }
    ]
  },
  %{
    title: "This is post 2",
    id: "uuid-uuid-uuid-uuid-2",
    comments: [
      %{
        message: "This is a post 2 message which in inactive",
        id: "uuid-uuid-uuid-message-4",
        is_active: false,
        is_active_last_updated: ~U[2024-03-15 15:50:18Z]
      }
    ]
  }
]

Notice how only the active and latest is_active_last_updated are selected.

How can I achieve this with ecto?

Obviously, I can do a preload of comments and sort and select them manually. But I think there has to be a better way of handling such requirements. Possibly in a single dynamic query/subquery?

Any help is appreciated.
Thanks.

First Post!

ken-kost

ken-kost

subquery could maybe be something like:

Comment
|> order_by([:is_active, {:desc, :is_active_last_updated}])
|> limit(1)

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New

We're in Beta

About us Mission Statement