feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能 - 集成Gin、GORM、Viper、Zap等框架 - 添加密码加密、数据库操作、中间件等完整功能 - 配置多环境支持、日志轮转、CORS处理 - 创建完整的项目结构和配置文件体系
This commit is contained in:
76
Web开发/03go-gorm-demo/query_advanced.go
Normal file
76
Web开发/03go-gorm-demo/query_advanced.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
//type User struct {
|
||||
// ID uint `gorm:"primaryKey"`
|
||||
// Name string `gorm:"size:100"`
|
||||
// Email string `gorm:"size:100;unique"`
|
||||
// Age int
|
||||
// Active bool `gorm:"default:true"`
|
||||
// CreatedAt time.Time
|
||||
//}
|
||||
|
||||
func main() {
|
||||
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
|
||||
db.AutoMigrate(&User{})
|
||||
|
||||
// 插入测试数据
|
||||
users := []User{
|
||||
{Name: "Alice", Email: "alice@example.com", Age: 30, Active: true},
|
||||
{Name: "Bob", Email: "bob@example.com", Age: 25, Active: false},
|
||||
{Name: "Charlie", Email: "charlie@example.com", Age: 35, Active: true},
|
||||
{Name: "David", Email: "david@example.com", Age: 28, Active: true},
|
||||
}
|
||||
db.Create(users)
|
||||
|
||||
// 1. 多条件查询
|
||||
var result1 []User
|
||||
db.Where("age > ? AND active = ?", 25, true).Find(&result1)
|
||||
fmt.Printf("Age > 25 AND active: %d users\n", len(result1))
|
||||
|
||||
// 2. OR 查询
|
||||
var result2 []User
|
||||
db.Where("age < ? OR active = ?", 30, false).Find(&result2)
|
||||
fmt.Printf("Age < 30 OR inactive: %d users\n", len(result2))
|
||||
|
||||
// 3. 模糊查询
|
||||
var result3 []User
|
||||
db.Where("name LIKE ?", "%li%").Find(&result3)
|
||||
fmt.Printf("Name contains 'li': %d users\n", len(result3))
|
||||
|
||||
// 4. 仅查询指定字段
|
||||
var result4 []User
|
||||
db.Select("name", "email").Find(&result4)
|
||||
fmt.Printf("Selected fields: %d users\n", len(result4))
|
||||
for _, u := range result4 {
|
||||
fmt.Printf(" - %s (%s)\n", u.Name, u.Email)
|
||||
}
|
||||
|
||||
// 5. 统计查询
|
||||
var count int64
|
||||
db.Model(&User{}).Where("active = ?", true).Count(&count)
|
||||
fmt.Printf("Active users count: %d\n", count)
|
||||
|
||||
// 6. 聚合查询
|
||||
var avgAge float64
|
||||
db.Model(&User{}).Select("AVG(age)").Row().Scan(&avgAge)
|
||||
fmt.Printf("Average age: %.2f\n", avgAge)
|
||||
|
||||
// 7. 分组查询
|
||||
type Result struct {
|
||||
Active bool
|
||||
Count int64
|
||||
}
|
||||
var groupResult []Result
|
||||
db.Model(&User{}).Select("active, count(*) as count").Group("active").Scan(&groupResult)
|
||||
fmt.Println("Group by active:")
|
||||
for _, r := range groupResult {
|
||||
fmt.Printf(" Active=%v: %d users\n", r.Active, r.Count)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user