Skip to content

Commit

Permalink
DeriveActiveModel (SeaQL/sea-orm#240)
Browse files Browse the repository at this point in the history
  • Loading branch information
billy1624 committed Oct 18, 2021
1 parent 24f63c9 commit 45f004f
Show file tree
Hide file tree
Showing 2 changed files with 89 additions and 0 deletions.
2 changes: 2 additions & 0 deletions SeaORM/docs/01-index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
87 changes: 87 additions & 0 deletions SeaORM/docs/07-advanced-query/08-custom-active-model.md
Original file line number Diff line number Diff line change
@@ -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<T>` into `ActiveValue<T>` 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<i32>,
}
```

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<Option<T>>` allows for `Some(None)` to update the column to be NULL.

```rust
#[derive(DeriveIntoActiveModel)]
pub struct UpdateFruit {
pub cake_id: Option<Option<i32>>,
}

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),
}
);
```

0 comments on commit 45f004f

Please sign in to comment.