Expand description
Entities and the types and traits that describe them.
In SeaORM, every database table is represented by an Entity — a unit
struct implementing EntityTrait. The Entity ties together:
- the table’s name (via
EntityName), - its columns (via
ColumnTraitand the strongly-typedCOLUMNconstant), - its primary key (via
PrimaryKeyTrait/PrimaryKeyToColumn), - its relations to other entities (via
RelationTrait; in 2.0, relations can also be declared directly on theModelstruct asHasOne/HasManyfields).
Each Entity has two companion types:
Model— a plain struct mirroring a row of the table, used for reads.ActiveModel— a struct where every field is wrapped inActiveValue, used for inserts and partial updates.
From an Entity you can build select, insert, update, and delete queries
via EntityTrait::find, EntityTrait::insert, EntityTrait::update,
and EntityTrait::delete (plus their _many / _by_id siblings).
§Defining an Entity (2.0 dense format)
The recommended way to define an entity in SeaORM 2.0 is the dense entity
format, where the relations live directly on the Model struct as
HasOne / HasMany fields:
mod cake {
use sea_orm::entity::prelude::*;
#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "cake")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
#[sea_orm(has_many)]
pub fruits: HasMany<super::fruit::Entity>,
}
impl ActiveModelBehavior for ActiveModel {}
}§Defining an Entity (1.0 compact format)
The 1.0 compact format remains supported. Here relations are declared as a
separate Relation enum implementing RelationTrait, plus an explicit
Related impl per foreign entity:
mod cake {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "cake")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub name: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::fruit::Entity")]
Fruit,
}
impl Related<super::fruit::Entity> for Entity {
fn to() -> RelationDef {
Relation::Fruit.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
}Entity files are usually generated for you with sea-orm-cli against an
existing database. See the crate-level documentation for a
walkthrough of the most common operations.
Re-exports§
pub use compound::EntityLoaderTrait;pub use ActiveValue::NotSet;pub use ActiveValue::Set;pub use ActiveValue::Unchanged;
Modules§
- compound
- prelude
- Re-exports the types and traits most commonly needed to define and use
entities. Glob-import this module in entity files:
use sea_orm::entity::prelude::*;.
Structs§
- Bool
Column - Borrowed
Identity Iter - Borrowing iterator over the columns of an
Identity. - Bytes
Column - Column
Def - Schema metadata for a single column: SQL type, nullability, defaults, constraints, and other DDL-level options.
- Date
Like Column - Supports both chrono and time Date
- Date
Time Like Column - Supports both chrono and time DateTime
- Generic
Array Column - IpNetwork
Column - Json
Column - Numeric
Array Column - Numeric
Column - A column of numeric type, including integer, float and decimal
- Numeric
Column Nullable - A column of numeric type, including integer, float and decimal that is also nullable
- Owned
Identity Iter - Owning iterator over the columns of an
Identity(returned byIntoIterator for Identity). - Relation
Builder - Fluent builder for a
RelationDef. Construct one viaEntityTrait::belongs_to/has_one/has_many. - Relation
Def - Concrete description of a relation between two entities: which tables
and columns participate, whether
Selfis the FK-owning side, and the optional foreign-key constraint metadata. - Seaography
Column Attr - Column-level attributes consumed by Seaography when generating GraphQL schemas.
- String
Column - String
Column Nullable - Text
Uuid Column - Time
Like Column - Supports both chrono and time Time
- Uuid
Column
Enums§
- Active
Model Action - Which save operation an
ActiveModelis about to perform — used by hooks and helpers that need to branch on the kind of write. - Active
Value - The state of a field in an ActiveModel.
- Column
Type - All column types
- HasMany
Model - State carried by a
has_many(or many-to-many) field on anActiveModelEx. Chooses between “leave alone”, “additive write”, and “destructive replace” semantics. - HasOne
Model - State carried by a
belongs_toorhas_onefield on anActiveModelEx. Mirrors theNotSet/Setshape ofActiveValuebut for a related model. - Identity
- A one-or-many column identifier — the abstraction SeaORM uses to refer to either a single column or a composite (e.g. a composite primary key or foreign key).
- Relation
Type - Cardinality of a relation.
- Value
- Value variants
Traits§
- Active
Enum - A Rust representation of enum defined in database.
- Active
Enum Value - The Rust Value backing ActiveEnums
- Active
Model Behavior - Lifecycle hooks for an
ActiveModelTrait. - Active
Model Trait - The editable counterpart of a
Model, used to buildINSERTandUPDATEstatements. - Arrow
Schema with-arrow - Apache Arrow schema for an entity.
- Column
Trait - Operations and comparisons available on every entity column.
- Column
Type Trait - Extension methods on
ColumnTypefor buildingColumnDefs and inspecting databaseENUMmetadata. - Entity
Name - Names the SQL table backing an
Entity, plus the optional schema and comment metadata. - Entity
Trait - The contract every SeaORM entity implements — a static description of a table plus the CRUD entry points used to query it.
- From
Query Result - Construct a value from a
QueryResultrow. - Iden
Static - An identifier (table or column name) that can be borrowed as a
&'static str. - Identity
Of - Conversion into an
Identitywhose columns are guaranteed to belong to entityE. Used byRelationBuilder::from/toso the type system enforces that relation columns reference the right table. - Into
Active Model - A Trait for any type that can be converted into an
ActiveModel, can be derived usingDeriveIntoActiveModel. - Into
Active Value - Any type that can be converted into an ActiveValue
- Into
Identity - Conversion into an
Identity. Implemented for&str/String, a single column iden, and tuples of column idens (for composites up to 12 columns). - Into
Option - Iterable
- This trait designates that an
Enumcan be iterated over. It can be auto generated using theEnumIterderive macro. - Linked
- A multi-hop traversal between two entities: a chain of
LinkDefhops fromFromEntitytoToEntity. - Model
Trait - The interface implemented by every Model — an instance of an
EntityTrait, roughly an OOP “object” whose fields are the table’s columns. - Partial
Model Trait - A partial projection of a
Model— a struct that holds only some of the entity’s columns, used to avoid overfetching inSELECTqueries. - Primary
KeyArity - Number of columns a primary key spans — 1 for a single-column key,
nfor a composite key represented as ann-tuple. - Primary
KeyTo Column - Conversion between an entity’s
PrimaryKeyenum and itsColumnenum. Generated alongsidePrimaryKeyTraitfor every entity. - Primary
KeyTrait - Describes the primary key of an entity: which column variants make it up, the Rust value type (a tuple for composite keys), and whether the database auto-generates it.
- Related
Selfis related to entityR, which lets queries join the two tables without a manualONclause. For many-to-many relations, overrideviato point at the junction table.- Related
Self Via - Self-referential many-to-many relation:
Self <-> Selfthrough a junction table (e.g.user_follower). - Relation
Trait - Each variant of an entity’s
Relationenum implements this trait, providing theRelationDefthat backs joins, foreign keys, and related-model lookups. - TryInto
Model - Fallible conversion into a
ModelTraitvalue.
Functions§
- Unset
Deprecated - Defines an not set operation on an ActiveValue
Type Aliases§
- Foreign
KeyAction ON DELETE/ON UPDATEaction attached to a foreign key. Re-exported fromsea_queryfor convenience.- LinkDef
- One hop in a multi-hop
Linkedchain. Alias forRelationDef.