go语言对gorm不固定条件查询封装

2 篇文章 0 订阅
主要对gorm不定条件查询数据时的一个封装【灵感来于laravel项目中对db的封装laravel版本DB,EloquentORM不固定条件查询封装

封装方法在 app/models/entity/Gorm.go文件里

条件说明

[“字段名”,“操作符”,“查询值”,“与前一个条件的关系[默认and]”] \

1.如果是等于,可以省略"操作符" :
[]interface{}{“username”, “chen”} 或 []interface{}{“username”,"=" , “chen”}

2.大于:
[]interface{}{“createtime”, “>”, “2019-1-1”}

3.如果为or,那就得一写全:
[]interface{}{“username”, “=”, “chen”, “or”}

4.其它的where兼容gorm的where方法

测试

启动项目

go run main.go

访问测试地址:
http://127.0.0.1:8100/api/v1/user/test

带分页的地址:http://127.0.0.1:8100/api/v1/user/list

1、and条件测试

where := []interface{}{
	[]interface{}{"id", "=", 1},
	[]interface{}{"username", "chen"},
}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECT * FROM `users`  WHERE (id = 1)and(username = 'chen')

2、结构体条件测试

where := user.User{ID: 1, UserName: "chen"}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECT * FROM `users`  WHERE (id = 1) and (username = 'chen')

3、in,or条件测试

where := []interface{}{
	[]interface{}{"id", "in", []int{1, 2}},
	[]interface{}{"username", "=", "chen", "or"},
}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECT * FROM `users`  WHERE (id in ('1','2')) OR (username = 'chen')

3.1、not in,or条件测试

where := []interface{}{
	[]interface{}{"id", "not in", []int{1}},
	[]interface{}{"username", "=", "chen", "or"},
}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECT * FROM `users`  WHERE (id not in ('1')) OR (username = 'chen')

4、map条件测试

where := map[string]interface{}{"id": 1, "username": "chen"}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECT * FROM `users`  WHERE (`users`.`id` = '1') AND (`users`.`username` = 'chen')

5、and,or混合条件测试

where := []interface{}{
	[]interface{}{"id", "in", []int{1, 2}},
	[]interface{}{"username = ? or nickname = ?", "chen", "yond"},
}
db, err = entity.BuildWhere(db, where)
db.Find(&users)
// SELECTSELECT * FROM `users`  WHERE (id in ('1','2')) AND (username = 'chen' or nickname = 'yond')

//注:不要使用下方方法
/*
where := []interface{}{
	[]interface{}{"id", "in", []int{1, 2}},
	[]interface{}{
		[]interface{}{"username", "=", "chen"},
		[]interface{}{"username", "=", "yond", "or"},
	},
}
// 返回sql: SELECT * FROM `users`  WHERE (id in ('1','2')) AND (username = 'chen') OR (username = 'yond')
// 与设想不一样
// 经过测试,gorm底层暂时不支持db.Where(func(db *gorm.DB) *gorm.DB {})闭包方法
*/

####还支持分页查询,详见github
基于gin写的一个demo框架
https://github.com/qicmsg/go_vcard

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值