我想要一个带有父标记和子标记的标记,这样tag.parents
和tag.children
都会返回不同的标记列表。
这可以不写我自己的查询吗?
答案 0 :(得分: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)
标签a,b 的