JSONB - 按索引更新数组值
JSONB - update array value by index
如何通过索引更新JSON(B)数组值?还要检索 JSONB 数组中每个值的索引?
有ServiceStack ORMLite模型:
public class Page
{
[AutoIncrement]
public long Id { get; set; }
[PgSqlJsonB]
public List<Widget> Widgets { get; set; }
}
例如,如何更新Widgets列表中的第二项?
下面是一个示例,说明如何在原始 Postgres SQL 中执行 select 数组索引和通过索引更新数组值:
How to update objects inside JSONB
想法是 select 使用 AutoQuery 进行数组索引并更新特定的 JSONB 数组值,知道它在数据库数组中的索引。
在 OrmLite 中,像 List<Widget>
这样的复杂类型是斑点化的,所以如果你在 C# 中更改值并保存它,它会将整个 Widgets
属性 序列化为 JSON 并更新整个字段。
如果您想使用 PostgreSQL 原生函数来操作服务器端查询中的列内容,您需要使用 Custom SQL APIs,例如:
db.Execute("UPDATE page SET widgets = jsonb_set(widgets, ...) WHERE id = @id",
new { id });
如何通过索引更新JSON(B)数组值?还要检索 JSONB 数组中每个值的索引?
有ServiceStack ORMLite模型:
public class Page
{
[AutoIncrement]
public long Id { get; set; }
[PgSqlJsonB]
public List<Widget> Widgets { get; set; }
}
例如,如何更新Widgets列表中的第二项?
下面是一个示例,说明如何在原始 Postgres SQL 中执行 select 数组索引和通过索引更新数组值: How to update objects inside JSONB
想法是 select 使用 AutoQuery 进行数组索引并更新特定的 JSONB 数组值,知道它在数据库数组中的索引。
在 OrmLite 中,像 List<Widget>
这样的复杂类型是斑点化的,所以如果你在 C# 中更改值并保存它,它会将整个 Widgets
属性 序列化为 JSON 并更新整个字段。
如果您想使用 PostgreSQL 原生函数来操作服务器端查询中的列内容,您需要使用 Custom SQL APIs,例如:
db.Execute("UPDATE page SET widgets = jsonb_set(widgets, ...) WHERE id = @id",
new { id });