Search code examples
sqlelixirsql-likeecto

Like query on Integer primary key Id


In ecto I can write

query = from q in CustomerModel, where: like(q.id, "%1")
#Ecto.Query<from c in Qber.V1.CustomerModel, where: like(c.id, "%1")>

and when I run this query I get

(undefined_function): operator does not exist: integer ~~ unknown

from this question I got the idea that I have to Cast before applying Like on ID. So in Postgres, I can simply write this query as

SELECT * FROM customers WHERE CAST(id AS TEXT) LIKE '1%';

How do I apply cast in ecto before apply Like?


Solution

  • You can use fragment to create a query identical to what you want:

    query =
      from q in CustomerModel,
        where: like(fragment("CAST(? AS TEXT)", q.id), "1%")