-
Notifications
You must be signed in to change notification settings - Fork 9
Insert新增数据
Tuuz edited this page Jun 20, 2022
·
14 revisions
先建立Model标签,你也可以使用Struct
const Table = "tableprefix_tablename"
func Api_insert(qq, token, ip interface{}) bool {
db := tuuz.Db().Table(table)
data := map[string]interface{}{
"qq": qq,
"token": token,
"ip": ip,
}
db.Data(data)
_, err := db.Insert()
if err != nil {
Log.Dbrr(err, tuuz.FUNCTION_ALL())
return false
} else {
return true
}
}
func Api_insert(aid, uid, name, img, gender, phone, mtid, status interface{}) int64 {
db := tuuz.Db().Table(Table)
data := map[string]interface{}{
"aid": aid,
"uid": uid,
"name": name,
"img": img,
"gender": gender,
"phone": phone,
"mtid": mtid,
"status": status,
}
db.Data(data)
ret, err := db.InsertGetId()
if err != nil {
Log.Dbrr(err, tuuz.FUNCTION_ALL())
return 0
} else {
return ret
}
}
type Interface struct {
Db gorose.IOrm
}
func (self *Interface) Api_insert(aid, uid interface{}) int64 {
db := self.Db.Table(Table)
data := map[string]interface{}{
"aid": aid,
"uid": uid,
}
db.Data(data)
ret, err := db.InsertGetId()
if err != nil {
Log.Dbrr(err, tuuz.FUNCTION_ALL())
return 0
} else {
return ret
}
}
-
需求:
-
需要先插入uid1
-
如果uid1插入成功,才能插入uid2
-
如果成功两条都成功,如果失败,则一条都不能插入
-
写法:
-
1.使用上述方法3编写Model层
-
2.在Controller或者Action中(根据你的架构而定)编写如下代码
-
3.初始化数据库
-
4.执行Begin
-
5.确保所有return前一定Rollback
-
6.确保最终执行结束前一定要Commit
db := tuuz.Db()
db.Begin()
var i UserModel.Interface
i.Db = db
if id := i.Api_insert(aid1, uid1); id < 1 {
db.Rollback()
return
}
if id := i.Api_insert(aid1, uid2); id < 1 {
db.Rollback()
return
}
db.Commit()