I have created a function which will show the list of products or a single product with specific name lets say ‘Widget 1’ but how can I show the list of all products that starts with a letter ‘W’. I want to use like operator for the sql query as shown below:
select * from products where name like ‘%Widget 1%’;
but when I tried the like in my script it is showing error as shown below:
Ecto.Query.CompileError
#
p.name(like("%Widget 1%", order_by: [desc: p.id()], select: struct(p, [:id, :name, :quantity, :inserted_at, :updated_at]))) is not a valid query expression. If you want to invoke p.name/1 in a query, make sure that the module p is required and that name/1 is a macro
The working code is as shown below of my product module
def list_products do
query = from p in MyStore.Products.Product,
where: p.name == "Widget 1",
order_by: [
desc: p.id
],
select: struct(
p,
[:id, :name, :quantity, :inserted_at, :updated_at]
)
products = MyStore.Repo.all(query)
end