嘿,我正在创建一个 API 来返回用户及其个人资料
我有来自两个独立数据库的两个表,用户和配置文件
fn handle(
&mut self,
query_strings: SearchUsersQueryStrings,
_: &mut SyncContext<Self>,
) -> Self::Result {
let gateway_conn: &PgConnection = &self.1.get().unwrap();
let own_conn: &PgConnection = &self.0.get().unwrap();
let pattern = format!("%{}%", query_strings.username);
let found_users = users
.filter(username.like(pattern))
.get_results::<User>(gateway_conn)?;
let profile = Profile::belonging_to(&found_users)
.load::<Profile>(own_conn)?
.grouped_by(&found_users);
let data = found_users.into_iter().zip(profile).collect();
Ok(data)
}
这里的坏处是数据类型 result 是 ,解析起来非常难看
[
[
{
"id": 22,
"username": "412212512",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4372717072327271717172717103242e222a2f6d202c2e" rel="noreferrer noopener nofollow">[email protected]</a>",
"avatar": null,
"created_at": "2022-02-21T09:31:29.855851"
},
[
{
"id": 3,
"user_id": 22,
"status": "qqq",
"description": "xxx",
"created_at": "2022-03-07T22:53:17.491532",
"updated_at": null,
"deleted_at": null
}
]
],
[
{
"id": 25,
"username": "1412drew212512",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="31000302004000004243544603030300030371565c50585d1f525e5c" rel="noreferrer noopener nofollow">[email protected]</a>",
"avatar": null,
"created_at": "2022-02-21T10:37:04.588795"
},
[]
],
]
但我想要这样的东西:
[
{
"id": 22,
"username": "1412212512",
"email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7c4d4e4f4d0d4d4e4e4e4d4e4e3c1b111d1510521f1311" rel="noreferrer noopener nofollow">[email protected]</a>",
"avatar": null,
"created_at": "2022-02-21T09:31:29.855851",
"profile": {
"id": 3,
"user_id": 22,
"status": "qqq",
"description": "xxx",
"created_at": "2022-03-07T22:53:17.491532",
"updated_at": null,
"deleted_at": null
},
....
]
如果我使用load
func 在配置文件查询上它将返回 Vec<Profile>
但每个用户都有一条 Profile 记录,如果我不使用 load
并使用first
相反,我无法使用 grouped_by
超过它
最佳答案
创建一个名为 UserAPI
的 struct
,如下所示:
pub struct UserAPI {
#[serde(flatten)]
pub user: User,
pub profile: Profile,
}
然后在压缩数据后执行以下操作:
fn handle(
&mut self,
query_strings: SearchUsersQueryStrings,
_: &mut SyncContext<Self>,
) -> Self::Result {
let gateway_conn: &PgConnection = &self.1.get().unwrap();
let own_conn: &PgConnection = &self.0.get().unwrap();
let pattern = format!("%{}%", query_strings.username);
let found_users = users
.filter(username.like(pattern))
.get_results::<User>(gateway_conn)?;
let profile = Profile::belonging_to(&found_users)
.load::<Profile>(own_conn)?
.grouped_by(&found_users);
let data = found_users.into_iter().zip(profile).collect();
let users_with_profile: Vec<UserAPI> = data
.into_iter()
.map(|(user, profile)| {
UserAPI {
user,
profile,
}
})
.collect();
Ok(users_with_profile)
}
关于Rust Diesel 一对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71392523/