Created
October 8, 2015 12:24
-
-
Save knewter/7fa4c3bc93268490988a to your computer and use it in GitHub Desktop.
ecto many to many query
This file contains hidden or 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
# -*- c-basic-offset: 2; indent-tabs-mode: nil -*- | |
defmodule Score.ContactTest do | |
use Score.TestCase | |
@joe %{name: "joe", email: "[email protected]", sign_in_count: 0} | |
@joe_changeset User.changeset(%User{}, :create, @joe) | |
@bob %{name: "bob", email: "[email protected]", sign_in_count: 0} | |
@bob_changeset User.changeset(%User{}, :create, @bob) | |
setup do | |
joe = Repo.insert!(@joe_changeset) | |
bob = Repo.insert!(@bob_changeset) | |
joe_bob = %{user1_id: joe.id, user2_id: bob.id} | |
Contact.changeset(%Contact{}, :create, joe_bob) | |
|> Repo.insert! | |
{:ok, joe: joe, bob: bob} | |
end | |
test "finding a user's contacts", meta do | |
query = Score.Query.User.contacts(meta.joe) | |
contacts = Repo.all(query) | |
|> Enum.map(&(&1.name)) | |
assert ^contacts = ["bob"] | |
end | |
end |
This file contains hidden or 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
defmodule Score.User do | |
has_many :contacts, Score.Contact, foreign_key: :user1_id | |
has_many :contact_connections, Score.Contact, foreign_key: :user2_id | |
end |
This file contains hidden or 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
defmodule Score.Query.User do | |
alias Score.Contact | |
alias Score.User | |
import Ecto.Query | |
def contacts(user=%User{}) do | |
from u in User, | |
join: c in assoc(u, :contacts), | |
inner_join: u1 in User, on: u1.id == c.user2_id, | |
where: c.user1_id == u.id, | |
select: u1 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the gist!
I have one question though. Do you really need the where clause in the query-user (
where: c.user1_id == u.id
)? Isn't that statement already included in thejoin: c in assoc(u, :contacts)