如何在 many_to_many 关联中添加和删除关系?

How to add and remove a relation in a many_to_many association?

因此,根据 Ecto 文档中的示例,我有以下内容:

defmodule Post do
  use Ecto.Schema
  schema "posts" do
    many_to_many :tags, Tag, join_through: "posts_tags"
  end
end

defmodule Tag do
  use Ecto.Schema
  schema "tags" do
    many_to_many :posts, Post, join_through: "posts_tags"
  end
end

现在有哪些不同的方法:

a) 将现有 post 与现有标签相关联。

b) 解除现有 post 与标签的关联。

请注意,我不想创建嵌套资源,而是我有一个 %Post{} 和一个 tag_id,我希望创建或破坏它们之间的关联。

我可以想到两种不需要为 post:

加载所有标签的方法
  1. 为连接创建一个模块 table,例如PostTag 然后 associate/disassociate 通过 creating/deleting 一个 PostTag 行:

    # web/models/post_tag.ex
    defmodule PostTag do
      use Ecto.Schema
    
      @primary_key false
      schema "posts_tags" do
        belongs_to :post, Post
        belongs_to :tag, Tag
      end
    end
    
    # Create association
    Repo.insert!(%PostTag(post_id: 1, tag_id: 2))
    
    # Remove association
    Repo.get_by(PostTag, post_id: 1, tag_id: 2) |> Repo.delete!
    
  2. 直接在posts_tags上使用Repo.insert_all/2Repo.delete_all/2 table:

    # Create assoication
    Repo.insert_all "posts_tags", [%{post_id: 1, tag_id: 2}]
    
    # Delete association
    Repo.delete_all "posts_tags", [%{post_id: 1, tag_id: 2}]