Skip to content

Instantly share code, notes, and snippets.

@hyone
Created April 7, 2016 10:46
Show Gist options
  • Save hyone/f6e1a064929f66ed5abcfb4f47c9aa34 to your computer and use it in GitHub Desktop.
Save hyone/f6e1a064929f66ed5abcfb4f47c9aa34 to your computer and use it in GitHub Desktop.
Ecto.Query を SQL に変換する ref: http://qiita.com/hyone/items/06fd744c54d701617a7d
# 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]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment