2017-04-10 13 views
1

を通じてhas_manyの私は、次のユーザー・モジュールがあります。エクト - 自己参照、

schema "accounts_users" do 
    has_many :friendships, Friendship 
    has_many :friends, through: [:friendships, :friend] 

    timestamps() 
    end 

友情モジュール:

schema "accounts_friendships" do 
    belongs_to :user, User 
    belongs_to :friend, User 

    timestamps() 
    end 

と友情の移行:私は作成することができます

def change do 
    create table(:accounts_friendships) do 
     add :user_id, references(:accounts_users, on_delete: :nothing) 
     add :friend_id, references(:accounts_users, on_delete: :nothing) 

     timestamps() 
    end 

    create index(:accounts_friendships, [:user_id]) 
    create index(:accounts_friendships, [:friend_id]) 
    end 

を次のようなユーザー1とユーザー2の間の新しい友情:

%Friendship{user_id: 1, friend_id: 2} |> Repo.insert() 

期待通りに動作がユーザー1のために働く:

Repo.all(Ecto.assoc(user1, :friendships)) # => [%Friendship{...}] 
Repo.all(Ecto.assoc(user1, :friends)) # => [%User{...}] 

しかし、ユーザー2のためではない:

Repo.all(Ecto.assoc(user2, :friendships)) # => [] 
Repo.all(Ecto.assoc(user2, :friends)) # => [] 

私はfriendsは、ユーザー2のために見つけることができない理由を理解するが、なぜありませんfriendships?関係に何か問題がありますか?

答えて

2

なぜ私はfriendsがユーザー2に見つからないのですが、友情はなぜですか?関係に何か問題がありますか?

friendshipsのでのみFriendshipuser分野に関するものです。クエリーはfriendships.user_id = 2のみを検索します。作成されたフレンドシップはuser_id = 1friend_id = 2だったため、何も返されません。

あなたが別のリレーションを作成することができ、userない、ユーザーがfriendある友情を返します。これは、reverse_friendshipsを言う:

has_many :reverse_friendships, Friendship, foreign_key: :friend_id 

user1reverse_friendshipsが、user2何もありませんuser1reverse_friendshipsを持っています。