Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Transactions 在与EXTO的事务中使用中间插入的结果_Transactions_Elixir_Phoenix Framework_Ecto - Fatal编程技术网

Transactions 在与EXTO的事务中使用中间插入的结果

Transactions 在与EXTO的事务中使用中间插入的结果,transactions,elixir,phoenix-framework,ecto,Transactions,Elixir,Phoenix Framework,Ecto,使用Exto v2.2.6,Phoenix 1.3 我有一个博客应用程序。当用户发表文章时,它会将其插入Post表中,然后获得该文章的最终id,并将其插入newsfeeditm表中。理想情况下,我希望这是一个交易 (我使用的是苦艾酒图形ql,因此我的插入返回必须是{:ok,post}) 我有一个工作函数,如下所示: def create_post_add_newsfeed(%{ title: title, content: content, user_id

使用Exto v2.2.6,Phoenix 1.3

我有一个博客应用程序。当用户发表文章时,它会将其插入
Post
表中,然后获得该文章的最终id,并将其插入
newsfeeditm
表中。理想情况下,我希望这是一个交易

(我使用的是苦艾酒图形ql,因此我的插入返回必须是
{:ok,post}

我有一个工作函数,如下所示:

  def create_post_add_newsfeed(%{
      title: title,
      content: content,
      user_id: user_id
    }) do

    case Repo.insert!(%Post{title: title, content: content, user_id: user_id}) do
      post ->
        case Repo.insert!(%Newsfeeditem{type: "user_creates_post", user_id: user_id, post_id: post.id}) do
          newsfeeditem ->
            {:ok, post}
          _ ->
            {:error, "Post not recorded in newsfeed"}
        end
      _ ->
      {:error, "Post not inserted"}
    end
  end
这段代码不是事务,它散发着回调臭味。在这里,exto.Multi似乎是一个更合适的工具,但我不知道如何获得
Post
insert的结果,以便将其插入
Newsfeed

我想做这样的事情

  def create_post_add_newsfeed(%{
      title: title,
      content: content,
      user_id: user_id
    }) do
    multi =
      Multi.new
        |> Multi.insert(:post, %Post{title: title, content: content, user_id: user_id})
        |> # Some intermediate step where I get the 'post' from the line above
        |> Multi.insert(:newsfeeditem, %Newsfeeditem{type: "user_creates_post", user_id: users_id, post_id: post.id})

    case Repo.transaction(multi) do
      {:ok, %{post: post}} ->
        {:ok, post}
      {:error, _} ->
        {:error, "Error"}
    end
  end

你知道如何做到这一点吗?

你可以使用
Multi.run/3
来实现这一点。传递给
Multi.run/3
的函数将收到参数的更改。您可以从中提取插入的
post
,并在
Multi.run
中为
newsfeeding
发布
Repo.insert
。函数应该返回
{:ok,{u}
{:error,{u}
,这正是
Repo.insert
返回的结果,因此您不需要在函数内部执行更多操作

Multi.new
|> Multi.insert(:post, %Post{title: title, content: content, user_id: user_id})
|> Multi.run(:newsfeeditem, fn %{post: post} ->
  Repo.insert(%Newsfeeditem{type: "user_creates_post", user_id: users_id, post_id: post.id})
end)