rod*_*tor 5 elixir ecto phoenix-framework
克隆Ecto模型/记录的最简单方法是什么?我有一个样品配方模型,包含许多成分和嵌入标签.
模型
defmodule App.Recipe do
use App.Web, :model
schema "recipes" do
field :name, :string
has_many :ingredients, App.Ingredient
embeds_many :labels, App.Label
end
Run Code Online (Sandbox Code Playgroud)
克隆配方记录 如何克隆配方记录并创建用于插入新配方记录的变更集?
recipe = Repo.get(App.Recipe, 1)
recipe_changeset = Ecto.Changeset.change(recipe)
# ... Steps for cloning record with embeds?
new_recipe = Repo.insert(recipe_changeset)
Run Code Online (Sandbox Code Playgroud)
克隆配方和成分,并为配料分配新配方ID
如何使用预装的ingrediens克隆配方记录以插入带有新成分的新配方记录?
recipe = Repo.get(App.Recipe, 1)
|> Repo.preload(:ingredients)
recipe_changeset = Ecto.Changeset.change(recipe)
# ... Steps for cloning records?
new_recipe = Repo.insert(recipe_changeset)
Run Code Online (Sandbox Code Playgroud)
小智 1
只需在再次插入之前删除该 id 即可。
Repo.get(App.Recipe, 1)
|> Repo.preload(:ingredients)
|> whatever_you_wanna_do
|> Map.delete(:id)
|> Repo.insert
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
704 次 |
| 最近记录: |