database/sql2go/dao_tpl.tpl

60 lines
1.7 KiB
Smarty
Raw Normal View History

2022-05-16 12:38:32 +08:00
// Package {PACKAGE} ...
//
// Description : {PACKAGE} ...
package {PACKAGE}
import (
"gorm.io/gorm"
"errors"
)
// {DATA_STRUCT_NAME} 数据库表的数据结构
{DATA_STRUCT}
// New{DATA_STRUCT_DAO} 获取DAO实例
func New{DATA_STRUCT_DAO}() *{DATA_STRUCT_DAO} {
return &{DATA_STRUCT_DAO}{
table : "{DB_TABLE_NAME}",
}
}
// {DATA_STRUCT_DAO} sql2go tool generate
type {DATA_STRUCT_DAO} struct {
table string
}
// GetDetailBy{PRIMARY_KEY} 根据主键ID获取详情
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) GetDetailBy{PRIMARY_KEY}(dbInstance *gorm.DB, {PRIMARY_KEY} {PRIMARY_KEY_TYPE}) (*{DATA_STRUCT_NAME}, error) {
var (
err error
detail {DATA_STRUCT_NAME}
)
if err = dbInstance.Table({DAO_RECEIVER}.table).Where("{PRIMARY_KEY_FIELD} = ?", {PRIMARY_KEY}).Limit(1).First(&detail).Error; nil != err {
return nil, err
}
return &detail, nil
}
// GetList 获取数据列表
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) GetList(dbInstance *gorm.DB, condition map[string]interface{}, limit int, offset int) ([]{DATA_STRUCT_NAME}, error) {
if nil == condition {
condition = make(map[string]interface{})
}
var (
err error
list []{DATA_STRUCT_NAME}
)
if err = dbInstance.Table({DAO_RECEIVER}.table).Where(condition).Limit(limit).Offset(offset).Find(&list).Error; nil != err {
return make([]{DATA_STRUCT_NAME}, 0), err
}
return list, nil
}
// Create 创建数据
func ({DAO_RECEIVER} *{DATA_STRUCT_DAO}) Create(dbInstance *gorm.DB, data *{DATA_STRUCT_NAME}) error {
if nil == data {
return errors.New("data is nil")
}
return dbInstance.Table({DAO_RECEIVER}.table).Create(data).Error
}