Rust Diesel 一对一关系

标签 rust relationship actix-web rust-diesel

嘿,我正在创建一个 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超过它

最佳答案

创建一个名为 UserAPIstruct,如下所示:

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/

相关文章:

rust - 使用未声明的箱子或模块, "use crate_name::schema::posts"并不总是有效

rust - 如何配置 actix websocket 服务器的有效负载限制

rust - 我如何实现 std::convert::From 使其不消耗其输入?

rust - 两个使用者如何使用actix字段流?

ruby-on-rails - Rails 3 中的多对多关系

mysql - 如果基础对象是一个人,那么表示家庭内关系的最佳数据库结构是什么

rust - 使用 serde 反序列化带有 Enum 键的 HashMap

rust - 字符串连接错误 : expected a literal

python - 不使用点符号间接访问 Python 实例属性

rust - Actix CORS。从浏览器发送请求时出现问题