Skip to content

ActiveModelEx odd ActiveModelBehavior with a junction table #3010

@SpawnCycle

Description

@SpawnCycle

Description

When adding an entry related to a table through a junction table, the ActiveModelBehavior functions are not run for the junction table.

Steps to Reproduce

  1. Create M-N related tables (e.g. post-tag from tests/blogger)

Post:

#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "post")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub title: String,
    #[sea_orm(has_many, via = "post_tag")]
    pub tags: HasMany<super::tag::Entity>,
}

Tag:

#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "tag")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i32,
    pub tag: String,
    #[sea_orm(has_many, via = "post_tag")]
    pub posts: HasMany<super::post::Entity>,
}

Junction table:

#[sea_orm::model]
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "post_tag")]
pub struct Model {
    #[sea_orm(primary_key, auto_increment = false)]
    pub post_id: i32,
    #[sea_orm(primary_key, auto_increment = false)]
    pub tag_id: i32,

    pub a_field: String,

    #[sea_orm(belongs_to, from = "post_id", to = "id")]
    pub post: Option<super::post::Entity>,
    #[sea_orm(belongs_to, from = "tag_id", to = "id")]
    pub tag: Option<super::tag::Entity>,
}
  1. Define an ActiveModelBehavior function for the junction table
// for post_tag
#[async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, _insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        Ok(Self {
            a_field: Set("Set field".to_string()),
            ..self
        })

    }
}
  1. Insert using ActiveModelEx
    post::ActiveModelEx::new()
        .set_title("Post 1")
        .add_tag(tag::ActiveModelEx::new().set_tag("Tag 1"))
        .insert(db)
        .await?;

Expected Behavior

Insertion runs successfully with post_tag.a_field set to "Set field"

Actual Behavior

error returned from database: (code: 1299) NOT NULL constraint failed: post_tag.a_field

Reproduces How Often

Always errors for M-N, doesn't happen for 1-N or 1-1

Versions

Tested on Windows & Linux

sea-orm v2.0.0-rc.37
sea-orm-macros v2.0.0-rc.37 (proc-macro)
sea-bae v0.2.1 (proc-macro)
sea-query v1.0.0-rc.31
sea-query-derive v1.0.0-rc.12 (proc-macro)
sea-query-sqlx v0.8.0-rc.14
sea-query v1.0.0-rc.31 ()
sea-schema v0.17.0-rc.17
sea-query v1.0.0-rc.31 (
)
sea-query-sqlx v0.8.0-rc.14 (*)
sea-schema-derive v0.3.0 (proc-macro)

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions