gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Is there any Preload equivalent, but to use combined to gorm.Create?

Open silvioprog opened this issue 3 years ago • 2 comments

Your Question

Is there any Preload equivalent, but to use combined to gorm.Create? For example, image these structures:

type DocumentType struct {
	gorm.Model
	Description string `gorm:"type:varchar(20);not null;unique" validate:"required,lte=20"`
}

type Receiver struct {
	gorm.Model
	Name           string `gorm:"type:varchar(100);not null;unique" validate:"required,gte=2,lte=100"`
	DocumentTypeID *uint64
	DocumentType   *document_type.DocumentType
}

we can use the Preload like this, combined to Find, for example:

db.Debug().Preload("DocumentType").Find(&r) // "r" is a type "*Receiver"

so GORM retrieves the inner structure record automatically.

Is there any equivalent, but to use combined to Create? For example, something like this:

db.Debug().Preload("DocumentType").Create(&r)

The document you expected this should be explained

Some topic like Create with inner structures at: https://gorm.io/docs/create.html

Expected answer

It would be awesome if GORM could resolve the inner structure (to find its ID, for example) when creating nested records.

silvioprog avatar Sep 10 '22 18:09 silvioprog

Additional note: also tried using db.Debug().Preload("DocumentType").FirstOrCreate(&r), but also raises an error FOREIGN KEY constraint failed instead of creating the record.

silvioprog avatar Sep 10 '22 18:09 silvioprog

Fixed in my code by adding an additional method FillByDescription to the type DocumentType and calling in BeforeSave from Receiver:

func (r *Receiver) BeforeSave(tx *gorm.DB) (err error) {
	if err = validation.Check(r); err == nil && r.DocumentType != nil {
		_ = r.DocumentType.FillByDescription() // << HERE
	}
	return
}

func (r *Receiver) Create() error {
	return database.Create(r)
}

Anyway, let me know if we have something like this built-in in GORM.

silvioprog avatar Sep 10 '22 19:09 silvioprog