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
Elixir 长生不老药体外-如何插入/增加_Elixir_Phoenix Framework_Ecto - Fatal编程技术网

Elixir 长生不老药体外-如何插入/增加

Elixir 长生不老药体外-如何插入/增加,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我有一个模型,我想在凤凰城/长生不老药执行。该模型基本上计算用户花费金额的滚动总和。模型(收据)如下所示: --------------- | ID | Amount | --------------- | 1 | 0 | | ...| ... | | 5 | 4 | --------------- ID上有一个唯一的索引。我想在表中插入一个用户(我定义了ID),然后设置该用户不存在时的金额,否则将新金额添加到现有金额中。例如,执行: Repo.insert(Us

我有一个模型,我想在凤凰城/长生不老药执行。该模型基本上计算用户花费金额的滚动总和。模型(
收据
)如下所示:

---------------
| ID | Amount |
---------------
| 1  |   0    |
| ...|  ...   |
| 5  |   4    |
---------------
ID
上有一个唯一的索引。我想在表中插入一个用户(我定义了ID),然后设置该用户不存在时的金额,否则将新金额添加到现有金额中。例如,执行:

Repo.insert(Users.changeset(%Users{}, %{ID: 1, Amount: 10})
将导致:

---------------
| ID | Amount |
---------------
| 1  |   11   |
| ...|  ...   |
| 5  |   4    |
---------------
---------------
| ID | Amount |
---------------
| 1  |   11   |
| ...|  ...   |
| 5  |   4    |
| 6  |   5    |
---------------
执行Repo.insert(%Users{},Users.changeset(%%{ID:6,Amount:5})将导致:

---------------
| ID | Amount |
---------------
| 1  |   11   |
| ...|  ...   |
| 5  |   4    |
---------------
---------------
| ID | Amount |
---------------
| 1  |   11   |
| ...|  ...   |
| 5  |   4    |
| 6  |   5    |
---------------

我知道我应该用
:on_conflict
做点什么,但我有点不知道如何做对。有人能给我指出正确的方法吗?

当然,这是可能的。它看起来像这样:

iex> amount_to_add = 10
10
iex> Repo.get(User, 1)
nil
iex> Repo.insert(%User{id: 1, amount: amount_to_add}, conflict_target: :id, on_conflict: [inc: [amount: amount_to_add]])
...
iex> Repo.get(User, 1)
%User{id: 1, amount: 10, ...}
iex> Repo.insert(%User{id: 1, amount: amount_to_add}, conflict_target: :id, on_conflict: [inc: [amount: amount_to_add]])
...
iex> Repo.get(User, 1)
%User{id: 1, amount: 20, ...}

这是使用postgreSQL语法进行锁定的一种方法。我想您会找到其余的方法。

添加到第一个答案中 在更新后返回变量将防止并行问题

iex> Repo.insert(%User{id: 1, amount: amount_to_add},  returning: [:amount], conflict_target: :id, on_conflict: [inc: [amount: amount_to_add]])