forked from mirror/gorm
1.8 KiB
1.8 KiB
Migration
Auto Migration
Automatically migrate your schema, to keep your schema update to date
WARNING AutoMigrate will ONLY create tables, columns and indexes if doesn't exist, WON'T change existing column's type or delete unused columns to protect your data
db.AutoMigrate(&User{})
db.AutoMigrate(&User{}, &Product{}, &Order{})
// Add table suffix when create tables
db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
Has Table
// Check if model `User`'s table has been created or not
db.HasTable(&User{})
// Check table `users` exists or not
db.HasTable("users")
Create Table
db.CreateTable(&User{})
db.Set("gorm:table_options", "ENGINE=InnoDB").CreateTable(&User{})
// will append "ENGINE=InnoDB" to the SQL statement when creating table `users`
Drop table
db.DropTable(&User{})
ModifyColumn
Change column's type
// change column description's data type to `text` for model `User`'s table
db.Model(&User{}).ModifyColumn("description", "text")
DropColumn
db.Model(&User{}).DropColumn("description")
Add Foreign Key
// Add foreign key
// 1st param : foreignkey field
// 2nd param : destination table(id)
// 3rd param : ONDELETE
// 4th param : ONUPDATE
db.Model(&User{}).AddForeignKey("city_id", "cities(id)", "RESTRICT", "RESTRICT")
Indexes
// Add index
db.Model(&User{}).AddIndex("idx_user_name", "name")
// Multiple column index
db.Model(&User{}).AddIndex("idx_user_name_age", "name", "age")
// Add unique index
db.Model(&User{}).AddUniqueIndex("idx_user_name", "name")
// Multiple column unique index
db.Model(&User{}).AddUniqueIndex("idx_user_name_age", "name", "age")
// Remove index
db.Model(&User{}).RemoveIndex("idx_user_name")