【问题标题】:Create Ecto changeset for deeply nested struct with nested associations为具有嵌套关联的深度嵌套结构创建 Ecto 变更集
【发布时间】:2020-12-12 22:16:23
【问题描述】:

请考虑以下架构:

schema "businesses" do
  ...
  has_many :contacts, Contact
  has_many :conversations, Conversation
  ...
end
schema "contacts" do
  ...
  belongs_to :business, Business
  has_one :conversation, Conversation
  ...
end
schema "conversations" do
  ...
  belongs_to :business, Business
  belongs_to :contact, Contact
  has_many :messages, Message
  ...
end
schema "messages" do
  belongs_to :conversation, Conversation
  belongs_to :contact, Contact
end

鉴于我有一个business 结构,我将如何以处理关联的方式创建contactconversationmessage 结构?

排除messages 部分时以下工作。

business
|> Ecto.build_assoc(
  :contacts,
  %Contact{name: name, phone: phone}
)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(
  :conversation,
  %Conversation{business: business}
  |> Ecto.Changeset.change()
  |> Ecto.Changeset.cast_assoc(:business)
)
# |> Ecto.Changeset.put_assoc(:messages, [%Message{body: "hello"}])
|> Repo.insert()

由于倒数第二行未注释,PostgreSQL 让我知道message 应该有一个conversation_id,这是真的。怎么设置?

添加IO.inspect()

business
|> Ecto.build_assoc(
  :contacts,
  %Contact{name: name, phone: phone}
)
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(
  :conversation,
  %Conversation{business: business}
  |> Ecto.Changeset.change()
  |> Ecto.Changeset.cast_assoc(:business)
)
  |> IO.inspect()
# |> Ecto.Changeset.put_assoc(:messages, [%Message{body: "hello"}])
|> Repo.insert()

表明我们在尝试设置 messages 关联之前正在处理以下变更集:

#Ecto.Changeset<
  action: nil,
  changes: %{
    conversation: #Ecto.Changeset<action: :insert, changes: %{}, errors: [],
     data: #Conversation<>, valid?: true>
  },
  errors: [],
  data: #Contact<>,
  valid?: true

有没有办法让新创建的message两个新创建的contact 和新创建的conversation 关联?

【问题讨论】:

    标签: elixir associations ecto


    【解决方案1】:

    Ecto.Multi 可以做到这一点。

    https://hexdocs.pm/ecto/Ecto.Multi.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      相关资源
      最近更新 更多