提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
如何在GORM框架中使用Raw()方法+limit()+Offset()进行分页?
一、Raw()是什么?
在GORM中,Raw方法用于执行原始SQL语句。这个方法可以让你直接写SQL,而不是使用GORM的方法。这在你需要执行复杂的查询或者GORM不支持的操作时非常有用。
Raw方法接受一个字符串参数,这个字符串是你要执行的SQL语句。你可以在这个字符串中使用?作为占位符,然后在Raw方法的后面传入值来替换这些占位符。
代码如下:
var products []Product
result := db.Raw("SELECT * FROM products WHERE price > ?", 100).Scan(&products)
if result.Error != nil {
fmt.Println("Error:", result.Error)
} else {
fmt.Println("Products:", products)
}
二、Raw()方法怎么使用分页
1.简单SQL
代码如下(示例):
var products []Product
result := db.Raw("SELECT * FROM products LIMIT ? OFFSET ?", 10, 10).Scan(&products) // 获取第2页的数据
if result.Error != nil {
fmt.Println("Error:", result.Error)
} else {
fmt.Println("Products:", products)
}
2.通用方法(支持count)
代码如下(示例):
var products []Product
table := db.Raw("SELECT * FROM products").Scan(&products) // 获取第2页的数据
err = db.Table("(?) as a ", table).Count(&total).Limit(10).Offset(10).Scan(&products).Error
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Products:", products)
}
总结
使用db.Table()方法生成中间表后在进行操作