如何通过Ecto Multi从先前插入的表键中检索ID [英] How to retrieve id from previous inserted table key by Ecto Multi

查看:60
本文介绍了如何通过Ecto Multi从先前插入的表键中检索ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Ecto Multi从先前插入的表主键中检索ID.

I would like to retrieve id from previous inserted table primary key by Ecto Multi.

首先,我将插入到主表中.那么B明细表需要A.id.我尝试了以下代码.

At first, I insert to A main table. then B details table needs A.id. I tried following code.

Multi.new()
  |> Multi.insert(:insert, main)
  |> Multi.insert_all(:insert_all, B, details)
  |> Repo.transaction()

但是我不知道如何检索插入表B的A.id.我该怎么办?

However I have no idea how to retrieve A.id for insert table B. What I should do for it?

推荐答案

您可以执行以下示例,创建一个新的 User 记录和一个新的 Email 记录.(其中 email 记录通过 user_id 外键与父 user 记录相关联).

You can do something like the following example which creates a new User record and a new Email record (where the email record is associated to the parent user record via a user_id foreign key).

alias Ecto.Multi

user = get_user_params_from_form() # <-- or where-ever you are getting data
email = get_email_params_from_form()

Multi.new()
    |> Multi.insert(:user, User.changeset(%User{}, user))
    |> Multi.insert(
      :email,
      # Capture the id from the previous operation
      fn %{
           user: %User{
             id: user_id
           }
         } ->
        Email.changeset(%Email{user_id: user_id}, email)
      end
    )

我认为这证明了您描述的关系类型.希望对您有帮助!

I think this demonstrates the type of relationship you described. Hope it helps!

这篇关于如何通过Ecto Multi从先前插入的表键中检索ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆