How to retrieve id from previous inserted table key by Ecto Multi

后端 未结 2 1855
花落未央
花落未央 2021-01-26 14:51

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

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

2条回答
  •  花落未央
    2021-01-26 15:26

    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!

提交回复
热议问题