指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
①多个查询共用一个 tx *DB,查询句柄
比如 公共部分如下:
db := common.Db.Model(&model.Product{}).Select("id, kind, count(*) as total")

后面可以根据 不同条件进行操作:
db.Where(...)

②通过Scopes实现闭包查询功能

下面这个操作主要实现的是,where and or 功能,可以直接在where里面通过()将两个条件括起来,就像原生sql查询一样,其实这也是gorm的一个优势,直接可以在orm里写原生sql
//listTx := common.Db.Preload("Attributes").Where("kind = ? and (name like ? or properties like ?)", res.Kind.Kind, "%"+keywords+"%", "%"+keywords+"%")

//通过Scopes来实现闭包where查询,就像 laravel 一样,
listTx := common.Db.Preload("Attributes").Scopes(func(db *gorm.DB) *gorm.DB {
    return db.Where("name like ? or properties like ?", "%"+keywords+"%", "%"+keywords+"%")
})
--返回--