LoginSignup
5
4

More than 5 years have passed since last update.

Ecto.Query を SQL に変換する

Posted at

Ecto.Adapters.SQL.to_sql/3 を使えばいいみたい。

# iex -S mix
iex(1)> import Ecto.Query
nil
iex(2)> import Ecto.Adapters.SQL
nil

iex(3)> user_id = 2
2

iex(4)> q = from u in SampleApp.User, join: fu in assoc(u, :relationships), where: u.id == ^user_id, select: fu.id
#Ecto.Query<from u in SampleApp.User, join: r in assoc(u, :relationships),
where: u.id == ^2, select: r.id>

iex(5)> sql = to_sql(:all, SampleApp.Repo, q)
{"SELECT u1.\"id\" FROM \"users\" AS u0 INNER JOIN \"relationships\" AS r2 ON r2.\"follower_id\" = u0.\"id\" INNER JOIN \"users\" AS u1 ON u1.\"id\" = r2.\"followed_id\" WHERE (u0.\"id\" = $1)", [2]}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4