sea-orm icon indicating copy to clipboard operation
sea-orm copied to clipboard

Automatically update `created_at` & `updated_at` timestamp columns on update

Open billy1624 opened this issue 3 years ago • 1 comments

Motivation

This is a common feature for an ORM. Which "touch" these timestamp columns to record the last update timestamp and create at timestamp of a row.

Proposed Solutions

User can enable this feature by placing attribute on the corresponding field in the entity model.

#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "cake")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub name: String,
    #[sea_orm(updated_at)]
    pub updated_at: Option<DateTimeWithTimeZone>,
    #[sea_orm(created_at)]
    pub created_at: Option<DateTimeWithTimeZone>,
}

For insert, the value of both updated_at and created_at will be set to CURRENT_TIMESTAMP.

For update, the value of updated_at will be set to CURRENT_TIMESTAMP.

User can override this behaviour by setting the value of it explicitly, i.e. Set(xxx).

Additional Information

Related Discussions:

  • https://github.com/SeaQL/sea-orm/discussions/819

billy1624 avatar Jun 28 '22 09:06 billy1624

this feature is so useful. 👍 . I look forward to using it soon

baoyachi avatar Jul 12 '22 03:07 baoyachi

created_at should be an alias to on_insert = "current_timestamp". Merge into https://github.com/SeaQL/sea-orm/issues/1431

tyt2y3 avatar Jan 31 '23 06:01 tyt2y3