Replies: 4 comments 1 reply
-
|
Try this use sqlx::types::Json;
let _foos = sqlx::query_as!(
Foo,
r#"
SELECT
F.id,
COALESCE(
JSON_AGG(
JSON_BUILD_OBJECT(
'id', B.id,
'name', B.name
)
) FILTER (WHERE b.id IS NOT NULL),
'[]'
) as "blas!: Json<Vec<Bla>>"
FROM foos AS F
LEFT JOIN blas AS B ON B.foo_id = F.id
"#
)
.fetch_all(&pool); |
Beta Was this translation helpful? Give feedback.
1 reply
-
|
Yeah you need group by (sorry i forget to add it). Here's the complete tested code use sqlx::types::Json;
struct Foo {
id: i64,
blas: Json<Vec<Bla>>,
}
#[derive(Deserialize)]
struct Bla {
id: i64,
name: String,
}
let foos = sqlx::query_as!(
Foo,
r#"
SELECT
F.id,
COALESCE(
JSON_AGG(
JSON_BUILD_OBJECT(
'id', B.id,
'name', B.name
)
) FILTER (WHERE b.id IS NOT NULL),
'[]'
) as "blas!: Json<Vec<Bla>>"
FROM foos AS F
LEFT JOIN blas AS B ON B.foo_id = F.id
GROUP BY F.id
"#
)
.fetch_all(&pool)
.await?; |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
Still some weirdness going on: error[E0277]: the trait bound `Vec<Bla>: From<Json<Vec<Bla>>>` is not satisfied
--> src/main.rs:21:16
|
21 | let foos = sqlx::query_as!(
| ________________^
22 | | Foo,
23 | | r#"
24 | | SELECT
... |
38 | | "#
39 | | )
| |_____^ the trait `From<Json<Vec<Bla>>>` is not implemented for `Vec<Bla>`
thanks again |
Beta Was this translation helpful? Give feedback.
0 replies
-
|
@nouman2075 The only way I could get this working is with an intermediary representation of my object: use sqlx::PgPool;
#[derive(Debug)]
struct Foo {
id: i64,
blas: Vec<Bla>,
}
#[derive(Debug)]
struct Bla {
id: i64,
name: String,
}
#[derive(Debug)]
struct FooBlaRow {
id: i64,
bla_id: Option<i64>,
bla_name: Option<String>,
}
fn foos_from_row(rows: Vec<FooBlaRow>) -> Vec<Foo> {
let mut foos: Vec<Foo> = vec![];
for row in rows {
if foos.last().map(|i| i.id) != Some(row.id) {
foos.push(Foo {
id: row.id,
blas: vec![],
});
}
if let (Some(id), Some(name)) = (row.bla_id, row.bla_name) {
foos.last_mut().map(|i| i.blas.push(Bla { id, name }));
}
}
foos
}
#[tokio::main]
async fn main() {
let pool = PgPool::connect("postgres://test:test@localhost:25432/test")
.await
.unwrap();
let rows = sqlx::query_as!(
FooBlaRow,
r#"
SELECT
F.id as "id!",
B.id as "bla_id?",
B.name as "bla_name?"
FROM foos AS F
LEFT JOIN blas AS B ON B.foo_id = F.id
"#
)
.fetch_all(&pool)
.await
.unwrap();
println!("Rows {:#?}", rows);
let foos = foos_from_row(rows);
println!("foos {:#?}", foos);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am having a hard time using the query_as! macro.
I have the following schema
And these models:
I want to write a query that returns Foo and its Blas, but I have no idea how to do this.
I tried something like, but without success.
I'd appreciate some guidance here.
Beta Was this translation helpful? Give feedback.
All reactions