Ecto 中的多对多关系

Many to Many relationship in Ecto

我有一个用户模型和一个聊天模型。直观上随时会有多个人属于同一个聊天组,每个人可以有多个聊天组。因此聊天组必须属于多个user_id

我的聊天组和用户架构是:

schema "chatGroups" do
    field :name, :string
    has_many :messages, Message
    belongs_to :user, User

    timestamps
end

schema "users" do
    field :name, :string
    has_many :chatGroups, ChatGroup

    timestamps
end

有什么处理方法的建议吗?

Ecto 通过关系支持 has_many/3。这涉及在聊天组和用户之间创建中间 table。

您可以使用以下架构执行此操作:

chat_group.ex:

schema "chat_groups" do
  has_many :chat_group_users, MyApp.ChatGroupUser
  has_many :users, through: [:chat_group_users, :user]
end

chat_group_user.ex:

schema "chat_group_users" do
  belongs_to :chat_group, MyApp.ChatGroup
  belongs_to :user, MyApp.User
end

您也可以通过其他方式进行关联:

user.ex:

schema "users" do
  has_many :chat_group_users, MyApp.ChatGroupUsers
  has_many :chats, through: [:chat_group_users, :chat]
end

这使您可以执行以下操作:

Repo.get(Chat, 1) |> Repo.preload(:users)

这将为您的聊天模型获取用户并使用值填充 :user 键。

这是一个老问题,之前接受的答案不再是事实上的方式。

Ecto 现在支持 HABTM 或多对多关联。

https://hexdocs.pm/ecto/Ecto.Schema.html#many_to_many/3

many_to_many :users, MyApp.User, join_through: "chat_group_users"