siddhant3030
How can I write a raw sql query?
Hi,
I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw queries in phoenix. So to understand
I have created a user schema that inserts an email in a database table.
So created the changeset the like this
def changeset(user, attrs) do
user
|> cast(attrs, [:email, :password])
end
Now I have a create function that I’m using in my model. So the model will basically talk to db.
def create_user(attrs \\ %{}) do
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
I have inserted an email in my database. using this
iex(1) > user = User.changeset(%User{}, %{email: “”, password: “”})
Now what I want is to find that user by his email address.
Also If I wanted to fetch through id. I would just do this
def get_user!(id), do: Repo.get!(User, id)
But what if I want to write a raw query? How do I do that?
Marked As Solved
sribe
Ah! Seeing your result, I maybe see your problem. You’re expected the $1 inside the quotes to get replaced with the argument? Maybe what you actually want is:
Ecto.Adapters.SQL.query(Wizex.Repo, "SELECT * FROM game WHERE name ILIKE $1", [name <> "%"])
Also Liked
kokolegorille
You might also have a look at…
…for raw queries
al2o3cr
FWIW, you can do this with Repo.get_by(User, email: email_to_find).
benwilson512
The best place to start is always the docs. Hint: it’s a function inside this module Ecto.Repo — Ecto v3.14.0
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









