Pixabay |
In my real case, my current company has different convention of naming database column, so when I try to implement ORM, a lot of columns such as created_at, updated_at and deleted_at can't be generated automatically. also if you have a custom UUID you could pass the value UUID generator into hooks before the insert is executed. for more detail let's jump into code :
# Explanation
Above code containing model struct, and several methods from gorm to serve model, TableName method used to define table name if your structs name has different spelling, then next method is BeforeCreate, that is hooks method from gorm, this method have a standard convension to make it's work correctly, the structure is method need to implement model struct and passing gorm.DB reference param.
The above example is used to passing the uuid value into the ID column, and passing timestamp value into createdate column.
# The Advantages
if you are using hooks in order to passing value or executing statements before the query executed, your code is more centralized, readable and contextable. you don't need to pass all that value for each query statement you have define.