- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何与 ecto 2 建立多对多关系?作为一个示例应用程序,我想
创建一个可以在多个类别中的帖子。类别已经存在。例如:
[%Category{id: "1", name: "elixir"}, %Category{id: "2", name: "erlang"}]
defmodule Ecto2.Post do
use Ecto2.Web, :model
use Ecto.Schema
schema "posts" do
field :title, :string
many_to_many :categories, Ecto2.Category, join_through: "posts_categories", on_replace: :delete
timestamps
end
@required_fields ~w(title)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> cast_assoc(:categories) # not suitable?
end
end
defmodule Ecto2.Category do
use Ecto2.Web, :model
schema "categories" do
field :name, :string
timestamps
end
@required_fields ~w(name)
@optional_fields ~w()
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
post = Repo.get!(Post, 1) |> Repo.preload(:categories)
changeset = Post.changeset(post, %{"title"=> "bla", "categories"=> [%{id: "1"}]})
Repo.update!(changeset)
最佳答案
您可以通过传递像“posts_categories”这样的字符串来连接表,或者通过像 MyApp.PostCategory 这样的模式来连接模式。我更喜欢通过模式加入,因为可以包含时间戳。假设您选择通过架构而不是表加入:
def change do
create table(:posts_categories) do
add :post_id, references(:posts)
add :category_id, references(:categories)
timestamps
end
end
defmodule Ecto2.PostCategory do
use Ecto2.Web, :model
schema "posts_categories" do
belongs_to :post, Ecto2.Post
belongs_to :category, Ecto2.Category
timestamps
end
def changeset(model, params \\ %{}) do
model
|> cast(params, [])
end
end
many_to_many :categories, Ecto2.Category, join_through: Ecto2.PostCategory
many_to_many :posts, Ecto2.Post, join_through: Ecto2.PostCategory
post1 = Repo.get!(Post, 1)
category1 = Repo.get!(Category, 1)
post1
|> Repo.preload(:categories)
|> Post.changeset(%{})
|> put_assoc(:categories, [category1])
|> Repo.update!
关于Elixir ecto 2 创建 many_to_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529720/
无法将自定义模板添加到 sonata_type_model 多对多关系。我想覆盖标准模板 edit_orm_many_to_many.html.twig 写了这样的东西: ->add(
我正在尝试使用 ActiveRecord 在 Sinatra 中映射我的 MySQL dB。该数据库不遵循 ActiveRecord 约定,因此我需要将添加属性的所有内容映射到我的类。 一对多和一对一
如何与 ecto 2 建立多对多关系?作为一个示例应用程序,我想 创建一个可以在多个类别中的帖子。类别已经存在。例如: [%Category{id: "1", name: "elixir"}, %Ca
我是 Ecto 的新手。我在 Ecto 模式中定义了三个表,分别称为 User、Role 和 UserRole。在 UserRole 中,我需要更新附加字段(例如 “status”)以关联 User
我想自动更新有关模型更改的外部应用程序。问题是数据在事件 用户之间处于多对多关系。我尝试使用 "m2m_changed" signal . @receiver(m2m_changed, sender
我有两个 Ecto 模型:User 和 Skill,它们通过 users_skills 与 many_to_many 关联连接> 表: create table(:users_skills, prim
我遇到了以下问题:我想创建一个带有复选框的站点,用户可以在其中为某个任务选择其他用户(如涂鸦克隆)。到目前为止,我得到了一个 View ,它显示了所有当前可用的用户,但现在我想让用户选择其中哪一个正在
我是一名优秀的程序员,十分优秀!