JSON
Select JSON Result
All SeaORM selects are capable of returning serde_json::Value
.
// Find by id
let cake: Option<serde_json::Value> = Cake::find_by_id(1)
.into_json()
.one(db)
.await?;
assert_eq!(
cake,
Some(serde_json::json!({
"id": 1,
"name": "Cheese Cake"
}))
);
// Find with filter
let cakes: Vec<serde_json::Value> = Cake::find()
.filter(cake::Column::Name.contains("chocolate"))
.order_by_asc(cake::Column::Name)
.into_json()
.all(db)
.await?;
assert_eq!(
cakes,
[
serde_json::json!({
"id": 2,
"name": "Chocolate Forest"
}),
serde_json::json!({
"id": 8,
"name": "Chocolate Cupcake"
}),
]
);
// Paginate json result
let cake_pages: Paginator<_> = Cake::find()
.filter(cake::Column::Name.contains("chocolate"))
.order_by_asc(cake::Column::Name)
.into_json()
.paginate(db, 50);
while let Some(cakes) = cake_pages.fetch_and_next().await? {
// Do something on cakes: Vec<serde_json::Value>
}
Select JSON from raw SQL
let result: Vec<JsonValue> = JsonValue::find_by_statement(Statement::from_sql_and_values(
DbBackend::Postgres,
r#"SELECT "cake"."name" FROM "cake" GROUP BY "cake"."name"#,
[],
))
.all(&db)
.await?;
Convert JSON to ActiveModel
If you want to save user input into the database you can easily convert JSON value into ActiveModel
. You might want to skip deserializing some of the unwanted attributes.
Since
2.0.0
Not all fields of the Model need to be present in the JSON input, undefined fields will simply become ActiveValue::NotSet
.
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "fruit")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
pub cake_id: Option<i32>,
}
Set the attributes in ActiveModel
with set_from_json
method.
// An ActiveModel with primary key set
let mut fruit = fruit::ActiveModel {
id: ActiveValue::Set(1),
name: ActiveValue::NotSet,
cake_id: ActiveValue::NotSet,
};
// Note that this method will not alter the primary key values in ActiveModel
fruit.set_from_json(json!({
"id": 8,
"name": "Apple",
"cake_id": 1,
}))?;
assert_eq!(
fruit,
fruit::ActiveModel {
id: ActiveValue::Set(1),
name: ActiveValue::Set("Apple".to_owned()),
cake_id: ActiveValue::Set(Some(1)),
}
);
You can also create a new ActiveModel
from JSON value with the from_json
method.
let fruit = fruit::ActiveModel::from_json(json!({
"name": "Apple",
}))?;
assert_eq!(
fruit,
fruit::ActiveModel {
id: ActiveValue::NotSet,
name: ActiveValue::Set("Apple".to_owned()),
cake_id: ActiveValue::NotSet,
}
);