乐闻世界logo
搜索文章和话题

How do I create a TEXT column with Go Gorm

1个答案

1

When creating a database table using Go GORM, if you need to specify a column as TEXT type, you can set it using the gorm tag in the model definition. Here is a specific example:

go
package main import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) // Define a model, assuming we are creating a user model with extensive user description information, suitable for TEXT type User struct { ID uint `gorm:"primaryKey"` Name string `gorm:"size:255"` // Using varchar(255) by default Description string `gorm:"type:text"` // Specified as TEXT } func main() { // Initialize GORM and database connection db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("Database connection failed") } // Migrate schema, create table db.AutoMigrate(&User{}) // Create a new user user := User{Name: "John Doe", Description: "A long description about John Doe..."} db.Create(&user) // Query and print user information var queriedUser User db.First(&queriedUser, 1) // Query user with ID 1 println("User name:", queriedUser.Name) println("User description:", queriedUser.Description) }

In this example, we first define a User struct with ID, Name, and Description fields. For the Description field, we use the gorm:"type:text" tag to specify it as TEXT. Then, we initialize GORM and connect to an SQLite database, followed by using the AutoMigrate() method to create the table. Finally, we create and insert a User instance, then retrieve and print the user's information.

By doing this, you can easily define TEXT type columns in your database tables when using GORM.

2024年8月12日 18:16 回复

你的答案