在 Ecto 中更新时如何使用片段返回值
How to use fragment for returning a value when updating in Ecto
我需要在数据库中执行更新和 return 一个值。这可以使用 PostgreSQL
中的 RETURNING
关键字
因为 ecto 不支持,所以我想我必须使用 fragment 但我不确定该怎么做。这是我的:
query = from(v in MyModel,
where: v.id == ^instance_id,
update: [
inc: [counter: 1],
]
)
我想在更新后 return 一些字段,例如计数器和 ID,所以我需要添加到查询中:RETURNING id, counter
;
如果您使用 Ecto.Repo.update_all
https://hexdocs.pm/ecto/Ecto.Repo.html#c:update_all/3 有一个选项:返回以传递返回的字段列表
:returning - selects which fields to return. When true, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Or false, where nothing is returned (the default). This option is not supported by all databases.
执行后你可以访问一个元组:
It returns a tuple containing the number of entries and any returned result as second element. If the database does not support RETURNING in UPDATE statements or no return result was selected, the second element will be nil.
像这样:
result = from(v in MyModel, where: v.id == ^instance_id)
|> MyRepo.update_all([inc: [counter: 1]], returning: [id, counter])
在 Ecto 3 中,不推荐使用 returning: true 的机会 update_all 以支持查询中的 select。所以你会像这样解决它:
result = from(v in MyModel, where: v.id == ^instance_id, select: {v.id, v.counter})
|> MyRepo.update_all([inc: [counter: 1]])
我需要在数据库中执行更新和 return 一个值。这可以使用 PostgreSQL
中的RETURNING
关键字
因为 ecto 不支持,所以我想我必须使用 fragment 但我不确定该怎么做。这是我的:
query = from(v in MyModel,
where: v.id == ^instance_id,
update: [
inc: [counter: 1],
]
)
我想在更新后 return 一些字段,例如计数器和 ID,所以我需要添加到查询中:RETURNING id, counter
;
如果您使用 Ecto.Repo.update_all
https://hexdocs.pm/ecto/Ecto.Repo.html#c:update_all/3 有一个选项:返回以传递返回的字段列表
:returning - selects which fields to return. When true, returns all fields in the given struct. May be a list of fields, where a struct is still returned but only with the given fields. Or false, where nothing is returned (the default). This option is not supported by all databases.
执行后你可以访问一个元组:
It returns a tuple containing the number of entries and any returned result as second element. If the database does not support RETURNING in UPDATE statements or no return result was selected, the second element will be nil.
像这样:
result = from(v in MyModel, where: v.id == ^instance_id)
|> MyRepo.update_all([inc: [counter: 1]], returning: [id, counter])
在 Ecto 3 中,不推荐使用 returning: true 的机会 update_all 以支持查询中的 select。所以你会像这样解决它:
result = from(v in MyModel, where: v.id == ^instance_id, select: {v.id, v.counter})
|> MyRepo.update_all([inc: [counter: 1]])