在ecto模型中插入/更新嵌套对象

时间:2016-10-22 23:37:38

标签: elixir phoenix-framework ecto

使用

等模型
defmodule MyApp.StorageMovement do
  use MyApp.Web, :model

  schema "storage_movements" do
    field :name, :string
    field :reference_datetime, Timex.Ecto.DateTime
    has_many :storage_product_movements, MyApp.StorageProductMovement

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(parse_params_date(params), [:name, :reference_datetime])
    |> validate_required([:name, :reference_datetime])
  end
end

如何使用单个帖子请求,将相关值挂起?比如,如果它包含带ID的内容,请更新它,如果它没有ID,请创建它等吗?

2 个答案:

答案 0 :(得分:0)

刚刚发现如果你改变这样的模型:

defmodule MyApp.StorageMovement do
  use MyApp.Web, :model

  schema "storage_movements" do
    field :name, :string
    field :reference_datetime, Timex.Ecto.DateTime
    has_many :storage_product_movements, MyApp.StorageProductMovement, on_replace: :delete

    timestamps()
  end

  @doc """
  Builds a changeset based on the `struct` and `params`.
  """
  def changeset(struct, params \\ %{}) do
    struct
    |> cast(parse_params_date(params), [:name, :reference_datetime])
    |> cast_assoc(:storage_product_movements, params["storage_product_movements"])
    |> validate_required([:name, :reference_datetime])
  end
end

它将自动通过params子数组并创建新实体(如果它们没有ID),删除那些存在于数据库但不存在于params数组中并更新具有ID的那些

答案 1 :(得分:-1)

我认为你正在寻找insert_or_update/2

来自文档:

result =
  case MyRepo.get(Post, id) do
    nil  -> %Post{id: id} # Post not found, we build one
    post -> post          # Post exists, let's use it
  end
  |> Post.changeset(changes)
  |> MyRepo.insert_or_update

case result do
  {:ok, struct}       -> # Inserted or updated with success
  {:error, changeset} -> # Something went wrong
end