Last active
August 29, 2015 14:15
-
-
Save brweber2/50aab5fd1b2d1761e4c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this creates an incorrect query b/c it joins account, account_user and user_api_key to client | |
# as it is piped through | |
query = DemoApp.Client | |
|> join(:inner, [c], b0 in assoc(c, :account)) | |
|> join(:inner, [b0], b1 in assoc(b0, :account_user)) | |
|> join(:inner, [b1], b2 in assoc(b1, :user_api_key)) | |
|> where([b1, b0], b1.id == ^user_id and b0.id == ^account_id) | |
|> preload([b0, b1, b2], [account: {b0, account_user: {b1, user_api_key: b2}}]) | |
|> select([c, b0, b1, b2], {c, b0, b1, b2}) | |
# this builds: | |
Ecto.Query<from c in DemoBe.Client, join: a0 in assoc(c, :account), | |
join: a1 in assoc(c, :account_user), join: u in assoc(c, :user_api_key), | |
where: c.id == ^1 and a0.id == ^1, select: {c, a0, a1, u}, | |
preload: [account: {c, [account_user: {a0, [user_api_key: a1]}]}]> | |
# working version | |
query = DemoBe.Client | |
|> join(:inner, [c], a0 in assoc(c, :account)) | |
|> join(:inner, [c, a0], a1 in assoc(a0, :account_user)) | |
|> join(:inner, [c, a0, a1], u in assoc(a1, :user_api_key)) | |
|> where([c, a0, a1, u], a1.id == ^user_id and a0.id == ^account_id) | |
|> preload([c, a0, a1, u], [account: {a0, account_user: {a1, user_api_key: u}}]) | |
|> select([c, a0, a1, u], {c, a0, a1, u}) | |
# this is the behavior I want | |
query = from c in DemoBe.Client, | |
join: b0 in assoc(c, :account), | |
join: b1 in assoc(b0, :account_user), | |
join: b2 in assoc(b1, :user_api_key), | |
where: b1.id == ^user_id and b0.id == ^account_id, | |
preload: [account: {b0, account_user: {b1, user_api_key: b2}}], | |
select: {c, b0, b1, b2} | |
# which builds: | |
Ecto.Query<from c in DemoBe.Client, join: a0 in assoc(c, :account), | |
join: a1 in assoc(a0, :account_user), join: u in assoc(a1, :user_api_key), | |
where: a1.id == ^1 and a0.id == ^1, select: {c, a0, a1, u}, | |
preload: [account: {a0, [account_user: {a1, [user_api_key: u]}]}]> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment