gen icon indicating copy to clipboard operation
gen copied to clipboard

Preload on create

Open dimitrovvlado opened this issue 2 years ago • 0 comments

Your Question

Hi Team,

Thanks for creating this great library. I've been using it for a while and it seems to have an answer to all requirements except preloading when creating an object. According to the documentation:

clause.Associations can work with Preload similar like Select when creating/updating, you can use it to Preload all associations

however when I do something like this:

//User is code-generated
type User struct {
  ID         int32
  Name       string
  CompanyID  int32
  Company    *Company
}
//Assuming there's a Company in the database with ID = 123
user := &User{Name: "John Doe", CompanyID: 123}
err := query.Q.User.WithContext(ctx).Preload(field.Associations).Create(user)
//at this point user.Company = nil
user, _ = query.Q.User.WithContext(ctx).Where(query.User.ID.Eq(user.ID)).Preload(field.Associations).First()
//at this point user.Company != nil

The user struct won't get populated with a *Company pointer and behind the curtains the library only does insert (no select).

If that's not the intended use of Preload in the create case, then what is an elegant way of preloading the user after it gets created?

I wanted to use Hooks, but there's a problem with that - Hooks need to be added in the same package with the model which really messes up project structure. Again according to the documentation:

demo
├── cmd
│   └── generate
│       └── generate.go # execute it will generate codes
├── dal
│   ├── dal.go # create connections with database server here
│   ├── model
│   │   ├── method.go # DIY method interfaces
│   │   └── model.go  # store struct which corresponding to the database table
│   └── query  # generated code's directory
|       ├── user.gen.go # generated code for user
│       └── gen.go # generated code
|       └── user.gen_test.go # generated unit test
├── biz
│   └── query.go # call function in dal/gorm_generated.go and query databases
├── config
│   └── config.go # DSN for database server
├── generate.sh # a shell to execute cmd/generate
├── go.mod
├── go.sum
└── main.go

If I'm putting all my business logic in biz/query.go, I can't add a hook to the user, because it's in a different package.

The document you expected this should be explained

https://github.com/go-gorm/gen#readme

Expected answer

  1. How to preload data when creating - insert and select will always work, but is there are more elegant way?
  2. An example of using hooks - is it a good design decision to add more files in the model package?

dimitrovvlado avatar Aug 24 '22 12:08 dimitrovvlado