2016-09-07 42 views
1

因此,按照在外生文檔的例子,我有以下幾點:如何在many_to_many關聯中添加和刪除關係?

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 

現在有哪些不同的方式:

一)關聯現有發佈一個現有的標籤。

b)從標籤取消關聯現有帖子。

注意我不想創建一個嵌套的資源,但情況是我有一個%Post{}和一個tag_id,我希望創建或銷燬它們之間的關聯。

回答

4

有兩種方法我能想到的,不需要加載所有標籤的帖子:

  1. 創建的連接表,例如一個模塊PostTag然後相關人員/創建/刪除PostTag行撇清:在posts_tags

    # 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. 使用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}]