📅  最后修改于: 2023-12-03 14:41:37.003000             🧑  作者: Mango
GORM is a powerful ORM for the Go programming language. It provides a lot of features and functionalities that makes working with databases much easier for developers. One of these functionalities is the support for boolean struct fields.
GORM allows you to define boolean fields in your struct tags using the bool
data type. Here's an example:
type User struct {
ID uint `gorm:"primary_key"`
Name string `gorm:"not null"`
IsAdmin bool `gorm:"default:false"`
}
In this example, IsAdmin
is a boolean field which has a default value of false
. This means that if we create a new user without specifying the value of IsAdmin
, it will default to false
.
user := User{Name: "John Doe"}
db.Create(&user)
When querying boolean fields in GORM, you can use comparison operators such as eq
and neq
to filter the results. Here's an example:
var isAdminUsers []User
db.Where("is_admin = ?", true).Find(&isAdminUsers)
var nonAdminUsers []User
db.Where("is_admin = ?", false).Find(&nonAdminUsers)
In this example, we are querying for users based on their IsAdmin
field. The first query returns all users that have IsAdmin
set to true
, while the second query returns all users that have IsAdmin
set to false
.
GORM's support for boolean struct fields makes it easier for developers to work with databases. By defining boolean fields in your struct tags, you can specify default values and filter the results using comparison operators.