row_to_json()
我正在尝试使用PostgreSQL 9.2 中添加的函数将查询结果映射到 JSON 。
我无法找出将连接行表示为嵌套对象的最佳方法(1:1 关系)
这是我尝试过的(设置代码:表,示例数据,然后是查询):
-- some test tables to start out with:
create table role_duties (
id serial primary key,
name varchar
);
create table user_roles (
id serial primary key,
name varchar,
description varchar,
duty_id int, foreign key (duty_id) references role_duties(id)
);
create table users (
id serial primary key,
name varchar,
email varchar,
user_role_id int, foreign key (user_role_id) references user_roles(id)
);
DO $$
DECLARE duty_id int;
DECLARE role_id int;
begin
insert into role_duties (name) values ('Script Execution') returning id into duty_id;
insert into user_roles (name, description, duty_id) values ('admin', 'Administrative duties in the system', duty_id) returning id into role_id;
insert into users (name, email, user_role_id) values ('Dan', 'someemail@gmail.com', role_id);
END$$;
查询本身:
select row_to_json(row)
from (
select u.*, ROW(ur.*::user_roles, ROW(d.*::role_duties)) as user_role
from users u
inner join user_roles ur on ur.id = u.user_role_id
inner join role_duties d on d.id = ur.duty_id
) row;
我发现如果我使用ROW()
,我可以将结果字段分成一个子对象,但它似乎仅限于一个级别。我无法插入更多AS XXX
语句,因为我认为在这种情况下我应该需要。
我获得了列名,因为::user_roles
在该表的结果的情况下,我转换为适当的记录类型,例如 with 。
这是该查询返回的内容:
{
"id":1,
"name":"Dan",
"email":"someemail@gmail.com",
"user_role_id":1,
"user_role":{
"f1":{
"id":1,
"name":"admin",
"description":"Administrative duties in the system",
"duty_id":1
},
"f2":{
"f1":{
"id":1,
"name":"Script Execution"
}
}
}
}
我想要做的是以我可以添加连接的方式为连接生成 JSON(同样 1:1 很好),并将它们表示为它们加入的父对象的子对象,即如下所示:
{
"id":1,
"name":"Dan",
"email":"someemail@gmail.com",
"user_role_id":1,
"user_role":{
"id":1,
"name":"admin",
"description":"Administrative duties in the system",
"duty_id":1
"duty":{
"id":1,
"name":"Script Execution"
}
}
}
}