在 Ecto/Phoenix 中实现更新计数器的最佳方法是什么?

pun*_*cse 1 ruby-on-rails elixir ecto phoenix-framework

在 ruby​​ on rails(active record) 中,我们可以通过调用update_counter方法来更新计数器 。例如在 Rails 中,您只需要编写:

  # For the Post with id of 5, decrement the comment_count by 1, and
  # increment the action_count by 1
  Post.update_counters 5, :comment_count => -1, :action_count => 1
  # Executes the following SQL:
  # UPDATE posts
  #    SET comment_count = comment_count - 1,
  #        action_count = action_count + 1
  #  WHERE id = 5
Run Code Online (Sandbox Code Playgroud)

考虑到我必须更新多列的计数器,有没有什么简单的方法可以在 elixir/phoenix 中做到这一点?

NoD*_*ame 6

或者,您可以使用以下inc选项进行类似的操作:

Post
|> where(id: 5)
|> Repo.update_all(inc: [comment_count: -1, action_count: 1])
Run Code Online (Sandbox Code Playgroud)