Closed
Description
Hello. Don't mean to bother for clarification, but I can't seem to find a straight forward answer about sqlx support for One to Many deserialization.
I have a one to many relation between two tables:
CREATE TABLE consumable (
id UUID NOT NULL DEFAULT uuid_generate_v1(),
name VARCHAR(255),
PRIMARY KEY (id)
);
CREATE TABLE serving (
id SERIAL PRIMARY KEY,
consumable_id UUID NOT NULL,
amount DECIMAL(12,4) NOT NULL,
kcal DECIMAL(12,4) NOT NULL,
CONSTRAINT fk_consumable
FOREIGN KEY(consumable_id)
REFERENCES consumable(id)
ON DELETE CASCADE
);
And these are the corresponding structs
#[derive(serde::Serialize, serde::Deserialize, sqlx::FromRow)]
#[sqlx(rename = "consumable")]
pub struct Consumable {
pub id: Uuid,
pub name: String,
pub servings: Vec<Serving>
}
#[derive(sqlx::FromRow, serde::Serialize, serde::Deserialize, sqlx::FromRow)]
#[sqlx(rename = "serving")]
pub struct Serving {
pub id: String,
pub amount: BigDecimal,
pub kcal: BigDecimal
}
Is there a way to write a query with query_as!
that will directly write to an instance of Consumable
Something like this
pub async fn consumable_by_id(path: web::Path<String>, pool: web::Data<PgPool>) -> impl Responder {
let id = path.0;
let consumable_or_error = sqlx::sqlx::query_as!(Consumable,
r#"
<SOME_QUERY_NOT_SURE_WHAT>
WHERE consumable.id = $1
"#,
id
)
.fetch_one(connection.get_ref())
.await;
match consumable_or_error {
Ok(consumable) => HttpResponse::Ok()
.content_type("application/json")
.json(consumable),
Err(_) => HttpResponse::InternalServerError().finish(),
}
}
Is this possible with sqlx or would I just have to query the tables separately and
compose the structs in rust?
Metadata
Metadata
Assignees
Labels
No labels