diff --git a/SeaORM/docs/01-index.md b/SeaORM/docs/01-index.md index c481735ae9a..f3b4aac689d 100644 --- a/SeaORM/docs/01-index.md +++ b/SeaORM/docs/01-index.md @@ -80,6 +80,8 @@ 6.7 [Streaming](/docs/advanced-query/streaming) + 6.8 [Custom Active Model](/docs/advanced-query/custom-active-model) + 7. Internal Design 7.1 [Traits and Types](/docs/internal-design/trait-and-type) diff --git a/SeaORM/docs/07-advanced-query/08-custom-active-model.md b/SeaORM/docs/07-advanced-query/08-custom-active-model.md new file mode 100644 index 00000000000..87c12ed87f5 --- /dev/null +++ b/SeaORM/docs/07-advanced-query/08-custom-active-model.md @@ -0,0 +1,87 @@ +# Custom Active Model + +A derive macro `DeriveIntoActiveModel` for implementing `IntoActiveModel` on structs. This is useful for creating your own struct with only partial fields of a model, for example an insert struct, or update struct. + +`IntoActiveValue` trait allows converting `Option` into `ActiveValue` automatically. + +```rust +// Define regular model as usual +#[derive(Clone, Debug, PartialEq, DeriveEntityModel)] +#[sea_orm(table_name = "fruit")] +pub struct Model { + #[sea_orm(primary_key)] + pub id: i32, + pub name: String, + pub cake_id: Option, +} +``` + +Create a new struct with some fields omitted. + +```rust +#[derive(DeriveIntoActiveModel)] +pub struct NewFruit { + // id is omitted + pub name: String, + // it is required as opposed to optional in Model + pub cake_id: i32, +} + +assert_eq!( + NewFruit { + name: "Apple".to_owned(), + cake_id: 1, + } + .into_active_model(), + fruit::ActiveModel { + id: Unset(None), + name: Set("Apple".to_owned()), + cake_id: Set(Some(1)), + } +); +``` + +`Option>` allows for `Some(None)` to update the column to be NULL. + +```rust +#[derive(DeriveIntoActiveModel)] +pub struct UpdateFruit { + pub cake_id: Option>, +} + +assert_eq!( + UpdateFruit { + cake_id: Some(Some(1)), + } + .into_active_model(), + fruit::ActiveModel { + id: Unset(None), + name: Unset(None), + cake_id: Set(Some(1)), + } +); + +assert_eq!( + UpdateFruit { + cake_id: Some(None), + } + .into_active_model(), + fruit::ActiveModel { + id: Unset(None), + name: Unset(None), + cake_id: Set(None), + } +); + +assert_eq!( + UpdateFruit { + cake_id: None, + } + .into_active_model(), + fruit::ActiveModel { + id: Unset(None), + name: Unset(None), + cake_id: Unset(None), + } +); +```