Does AsChangeset
skip referenced fields and primary key?
#4355
-
My SQL is: CREATE TABLE foo (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
thing INTEGER
);
CREATE TABLE foo_child (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
something INTEGER,
foo_id INTEGER NOT NULL REFERENCES foo(id)
) and corresponding structs: #[derive(Queryable, Selectable, Insertable, Identifiable, PartialEq, Debug, AsChangeset)]
#[diesel(table_name = crate::database::schema::foo)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Foo {
pub id: i32,
pub thing: Option<i32>
}
#[derive(Queryable, Selectable, Insertable, Identifiable, Associations, Debug, PartialEq, Default)]
#[diesel(belongs_to(Foo))]
#[diesel(table_name = crate::database::schema::foo_child)]
#[diesel(check_for_backend(diesel::sqlite::Sqlite))]
pub struct Child {
pub id: i32,
pub something: Option<i32>,
pub foo_id: i32,
} so my question is, when I create new row of insert_into(foo_child::table)
.values(&Child {
foo_id: value.id,
..Default::default()
})
.execute(connection)
.map_err(|e| e.to_string())?; Or there's better way to do it? Sorry if it's a duplicate. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Well, no. Diesel doesn't override |
Beta Was this translation helpful? Give feedback.
-
Diesel generally inserts/updates all fields to the provided values. So if you set something to 0 diesel will set the database field to zero. The only exception there are primary key fields for updates. The Identifiable derive is usefully for identifying a database entry, which requires a primary key value. For that by default the id field is used but you can specify one or more other fields via the All of this is explained in depth in the All About Inserts and All about Updates guides and the API documentation of the relevant derives. |
Beta Was this translation helpful? Give feedback.
Diesel generally inserts/updates all fields to the provided values. So if you set something to 0 diesel will set the database field to zero. The only exception there are primary key fields for updates.
In addition to that both Insertsable and AsChangeset have special behaviour for optional fields. If such a field is None for an insert statement the database side default value is used. For updates the field is skipped.
The Identifiable derive is usefully for identifying a database entry, which requires a primary key value. For that by default the id field is used but you can specify one or more other fields via the
#[diesel(primary_key())]
attribute.All of this is explained in depth in the …