gpt4 book ai didi

elixir - 如何在多对多关联中添加和删除关系?

转载 作者:行者123 更新时间:2023-12-02 08:18:52 26 4
gpt4 key购买 nike

因此,根据 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) 将现有帖子与现有标签相关联。

b) 取消现有帖子与标签的关联。

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

最佳答案

我可以想到两种不需要为帖子加载所有标签的方法:

  1. 为连接表创建一个模块,例如PostTag 然后通过创建/删除 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:

    # 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}]

关于elixir - 如何在多对多关联中添加和删除关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39375860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com