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