How to write if condition in middle of Ecto query

how do I write if condition in middle of query ? like this ? and is this way right?

post = Repo.all from p in PostCategory,
           join: c in assoc(p, :cms_post),
	   where: p.id == ^category_id,
	   if group_acl != "admin" do
	      where: p.group_acl == ^group_acl,
  	      where: c.group_acl == ^group_acl,
	   end
	   order_by: p.inserted_at,
	   limit: 10,
           preload: [cms_post: c]

Thanks

https://blog.drewolson.org/composable-queries-ecto/

Check out that link and scroll down to Query Composition. You want to build the whole query minus the stuff in the if first. Then in your condition if true form a new query composed with the first one or just the first one.

Roughly something like this:

query = from p in PostCategory, blah blah blah

query = if group_acl != "admin" do
  from p,c in query, blah blah
else
  query
end

Repo.all query
1 Like

thank you , unfortunately, I didn’t understand. may you edit my code ?

post = Repo.all from p in PostCategory,
           join: c in assoc(p, :cms_post),
	   where: p.id == ^category_id,
	   if group_acl != "admin" do
	      where: p.group_acl == ^group_acl,
  	      where: c.group_acl == ^group_acl,
	   end
	   order_by: p.inserted_at,
	   limit: 10,
           preload: [cms_post: c]

I just need to edit 2 lines which is below; can I do condition without creation again?

where: p.group_acl == ^group_acl,
where: c.group_acl == ^group_acl,

https://hexdocs.pm/ecto/Ecto.Query.html#select_merge/3

I’m seeing something what is the whole of all code will be edited by me, not part of it.

query = from p in PostCategory,
  join: c in assoc(p, :cms_post),
  where: p.id == ^category_id
  order_by: p.inserted_at,
  limit: 10,
  preload: [cms_post: c]

query = case group_acl do
  "admin" -> query
  _other -> 
    from [p, c] in query,
      where: p.group_acl == ^group_acl,
      where: c.group_acl == ^group_acl
end

post = Repo.all(query)
4 Likes