ashok

ashok

Insert multiple where clause based on user input params in Ecto query

I have a product listing page in which I want to give a search product option if the user enters any search term for product name or product price then the search term should be included in the final query otherwise I want to show full product list.

The query is written in my module to fetch all product having word “Widget” in the product name and product price less than $10 is as shown below:

def list_products(params) do
    query = from p in MyStore.Products.Product,
                 where: like(p.name,"%Widget%"),
                 where: p.price <= 10,
                 order_by: [
                   desc: p.id
                 ],
                 select: struct(
                   p,
                   [:id, :name, :quantity, :inserted_at, :updated_at]
                 )
    products = MyStore.Repo.paginate(query,params)
end

Now if the user enters Product name or Product price in the Product filter form I want to include that variable in my query instead of static where clause I have passed in above code. I need the “where” clause optional if user wants to filter product list then “where” clause should be added otherwise it should show the complete product list. It will be great if someone provides me the correct demo code based on the above query.

First Post!

kokolegorille

kokolegorille

The good way is to reduce a criteria list into a query…

Most Liked

kokolegorille

kokolegorille

Something like this… (it’s related to a User)

  def list_users_query(criteria \\ []) do
    query = from p in User

    Enum.reduce(criteria, query, fn
      {:limit, limit}, query ->
        from p in query, limit: ^limit

      {:offset, offset}, query ->
        from p in query, offset: ^offset

      {:filter, filters}, query ->
        filter_with(filters, query)

      {:order, order}, query ->
        from p in query, order_by: [{^order, ^@order_field}]

      {:preload, preloads}, query ->
        from p in query, preload: ^preloads

      arg, query ->
        Logger.info("args is not matched in query #{inspect arg}")
        query
    end)
  end

  defp filter_with(filters, query) do
    Enum.reduce(filters, query, fn
      {:name, name}, query ->
        pattern = "%#{name}%"
        from q in query, where: ilike(q.name, ^pattern)
    end)
  end

Then You could do…

iex> Accounts.list_users filter: [name: "dmi"], limit: 1 
11
Post #3

Last Post!

kokolegorille

kokolegorille

It’s optional… If You don’t pass criteria, it will not be used

You can also pass an order parameter.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
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
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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
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
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 44778 311
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

We're in Beta

About us Mission Statement