Your Question

Hello,

I'm trying to omit has-many association, without zeroing the value of the field (so I would get the expected foreign key constraint error), see the following example:

type Root struct {
    gorm.Model
    Name        string       `gorm:"not null,size:100;"`
    Steps  []Step
}

type Step struct {
    gorm.Model
    Name        string       `gorm:"not null,size:100;"`
    RootID uint         `gorm:"not null,uniqueIndex:idx_index_root_id;"`
    Root   Root    `gorm:"foreignKey:RootID;"`
}


DB.Debug().Omit("Root").Create(&step)

// Notice the `root_id` value is set to 0 in the log
// [1.061ms] [rows:0] INSERT INTO `steps` (`created_at`,`updated_at`,`deleted_at`,`name`,`root_id`) VALUES ("2023-03-25 08:29:29.26","2023-03-25 08:29:29.26",NULL,"1 Step",0) RETURNING `id`

I tried the advised approach for omitting many-to-many relations (docs), but seems it doesn't work with has-many:

DB.Debug().Omit("Root.*").Create(&step)

// Error
// 2023/03/25 08:29:49 /routes/queue.go:310 near "ON": syntax error [0.075ms] [rows:0] INSERT INTO `roots` DEFAULT VALUES ON CONFLICT DO NOTHING RETURNING `id`

The document you expected this should be explained

https://gorm.io/docs/associations.html#Skip-Auto-Create-x2F-Update

Expected answer

A way to omit auto creating has-many association without zeroing the field value

Comment From: cwww3

try to use Omit("RootID","Root")

Comment From: mrf345

Thanks so much @cwww3