Ecto 构建多个关联
Ecto build multiple assoc
目前正在使用 Ecto + Postgres 进行 Phoenix 项目。创建评论时,作为评论 belongs_to
用户和文章,有没有办法建立多个关联来生成一个变更集?
类似这样的伪代码
comment_changeset = build_assoc(article, :comment)
|> build_assoc(user, :comment)
有什么想法吗?
根据您的应用程序设置方式,您需要使用 cast_assoc/3
or put_assoc/4
文档中的相关部分是
In other words, cast_assoc/3
is useful when the associated data is managed alongside the parent struct, all at once. If each side of the association is managed separately, it is preferable to use put_assoc/3
and directly instruct Ecto how the association should look like.
正如 Justin 提到的那样,您可以使用 put_assoc
来做到这一点,所以在我的脑海中,我认为这样的事情应该可行。
comment_changeset =
article
|> Ecto.build_assoc(:comment)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:user, user)
目前正在使用 Ecto + Postgres 进行 Phoenix 项目。创建评论时,作为评论 belongs_to
用户和文章,有没有办法建立多个关联来生成一个变更集?
类似这样的伪代码
comment_changeset = build_assoc(article, :comment)
|> build_assoc(user, :comment)
有什么想法吗?
根据您的应用程序设置方式,您需要使用 cast_assoc/3
or put_assoc/4
文档中的相关部分是
In other words,
cast_assoc/3
is useful when the associated data is managed alongside the parent struct, all at once. If each side of the association is managed separately, it is preferable to useput_assoc/3
and directly instruct Ecto how the association should look like.
正如 Justin 提到的那样,您可以使用 put_assoc
来做到这一点,所以在我的脑海中,我认为这样的事情应该可行。
comment_changeset =
article
|> Ecto.build_assoc(:comment)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:user, user)