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

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New

Other popular topics Top

johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
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
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
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43806 214
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
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
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New

We're in Beta

About us Mission Statement