func(user User) BeforeCreate(tx *gorm.DB) { field := tx.Statement.Schema.LookUpField("Attrs") if field.DataType == "json" { // do something } }
GormDBDataType 通常在迁移时返回当前驱动程序的正确数据类型,例如
func(JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string { // use field.Tag, field.TagSettings gets field's tags // checkout https://github.com/go-gorm/gorm/blob/master/schema/field.go for all options
// returns different database type based on driver name switch db.Dialector.Name() { case"mysql", "sqlite": return"JSON" case"postgres": return"JSONB" } return"" }
// MySQL // SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.role') IS NOT NULL // SELECT * FROM `users` WHERE JSON_EXTRACT(`attributes`, '$.orgs.orga') IS NOT NULL
// PostgreSQL // SELECT * FROM "user" WHERE "attributes"::jsonb ? 'role' // SELECT * FROM "user" WHERE "attributes"::jsonb -> 'orgs' ? 'orga'
db.Find(&user, datatypes.JSONQuery("attributes").Equals("jinzhu", "name")) // MySQL // SELECT * FROM `user` WHERE JSON_EXTRACT(`attributes`, '$.name') = "jinzhu"
// PostgreSQL // SELECT * FROM "user" WHERE json_extract_path_text("attributes"::json,'name') = 'jinzhu'