2016-11-06 51 views

回答

0

我能夠做到這一點。我創建了一個tag_relationship表第一:

create table(:tag_relationship, primary_key: false) do 
    add :parent_id, references(:tags) 
    add :child_id, references(:tags) 
end 

給它一個架構&變更

defmodule Notebook.TagRelationship do 
    use Notebook.Web, :model 

    @primary_key false 
    schema "tag_relationship" do 
    belongs_to :parent, Tag 
    belongs_to :child, Tag 
    end 

    def changeset(struct, params \\ %{}) do 
    struct 
    |> cast(params, [:parent_id, :child_id]) 
    |> validate_required([:parent_id, :child_id]) 
    end 
end 

現在設置所有的標籤模型中的MANY_TO_MANY關係

schema "tags" do 
    field :name, :string 
    many_to_many :parents, Notebook.Tag, [join_through: Notebook.TagRelationship, 
    join_keys: [child_id: :id, parent_id: :id]] 
    many_to_many :children, Notebook.Tag, [join_through: Notebook.TagRelationship, 
    join_keys: [parent_id: :id, child_id: :id]] 
    timestamps() 
end 

我明確設置的鍵名因爲我不知道它會嘗試推斷什麼。

現在我可以創建一個TagRelationship變更

c = TagRelationships.changeset(%TagRelationship{}, 
     {parent_id: a.id, child_id: b.id}) 
Repo.insert(c) 

標籤爲一個關係,B