我有 2 张桌子(工作场所和工人)有一个:m 关系。我的目标是拥有一个workplace
结构,Vec
其中包含所有相关的workers
. 我想使用 sqlx 来做到这一点。使用 Diesel 对我来说不是一个选择。
这是我在数据库方面想出的:
CREATE TABLE workplaces (
id BIGSERIAL PRIMARY KEY,
place TEXT NOT NULL
);
CREATE TABLE workers (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE workplaces_workers (
workplace_id BIGINT NOT NULL REFERENCES workplaces (id) ON DELETE CASCADE,
workers_id BIGINT NOT NULL REFERENCES workers (id) ON DELETE CASCADE,
PRIMARY KEY (workplace_id, workers_id)
);
到目前为止,这是我的 rust 代码:
pub struct Workplace {
pub id: i64,
pub place: String,
pub workers: Option<Vec<Worker>>
}
pub struct Worker {
pub id: i64,
pub name: String
}
我尝试使用sqlx::query_as
宏,但我想不出一种方法来映射Vec<Worker>
pub async fn find_workplace(pool: &PgPool, id: &i64) -> Result<Option<Workplace>> {
return Ok(query_as!(Workplace, "SELECT * FROM workplaces wp
JOIN workplaces_workers wpws ON wp.id = wpws.workplace_id
JOIN workers ws ON wpws.workers_id = ws.id
WHERE wp.id = $1", id).fetch_optional(pool).await?)
}