Elixir 外星-自我参照,有很多通过

Elixir 外星-自我参照,有很多通过,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我有以下用户模块: 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,

我有以下用户模块:

  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)) # => []
我理解为什么用户2找不到
好友
,但为什么找不到
好友
?关系有问题吗

我理解为什么用户2找不到朋友,但为什么找不到朋友?关系有问题吗

因为
友谊
只与
友谊
用户
字段有关。您的查询只搜索
friendships.user\u id=2
,但不会返回任何内容,因为所创建的友谊具有
user\u id=1
Friends\u id=2

您可以创建另一个关系,例如
反向友谊
,它将返回用户是
朋友
,而不是
用户的友谊:

has_many :reverse_friendships, Friendship, foreign_key: :friend_id
现在
user1
将没有
reverse\u友情
,但是
user2
将有
reverse\u友情
user1