go-gorm / gen

Gen: Friendly & Safer GORM powered by Code Generation
https://gorm.io/gen/
MIT License
2.29k stars 296 forks source link

About GEN and gorm hook #812

Open NoSugarCoffee opened 1 year ago

NoSugarCoffee commented 1 year ago

Your Question

The GEN seems extract dao layer like java, but seems a little problem with gorm hook.

Imagine that:

// pkg models
type User
type UserChangeLog

// hook
func (user *User) afterUpdate(tx) error () {
  // if you want to record each changes
  query.userChangeLogDao.Insert("xxx")
}
// pkg dao or GEN "xx/query"
func (userDao) Update() {}
func (userChangeLogDao) Insert(User){}

it cause import cycle between dao and model because we also use dao api in model layer under the hook

so seems only can use raw gorm query under the hook or put GEN generated code to models/, is it right?

I have't use GEN with my project, but I think it can imporve our development efficiency and easy to write tests

The document you expected this should be explained

Expected answer

Give an advice about the question, thanks a lot.

nitwhiz commented 5 months ago

I have the same issue. This cannot be solved with the gorm hooks as long as they have to be defined on/for the model itself (func (m *Model) BeforeSave) because this inevitably creates the import cycle.

The only solution that comes to mind is having hooks outside of gorm called before db.Save(), which is ... not really nice.