add export func reame

添加函数支持
This commit is contained in:
谢小军
2020-01-12 21:41:47 +08:00
parent 3156708f37
commit 2211c3ca5d
19 changed files with 714 additions and 778 deletions

View File

@@ -36,7 +36,7 @@ func GetMysqlDbInfo() MysqlDbInfo {
// GetMysqlConStr Get MySQL connection string.获取mysql 连接字符串
func GetMysqlConStr() string {
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&interpolateParams=true",
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&interpolateParams=True",
_map.MySQLInfo.Username,
_map.MySQLInfo.Password,
_map.MySQLInfo.Host,

View File

@@ -9,6 +9,8 @@ import (
"github.com/jinzhu/gorm"
)
var gloabIsRelated bool // 全局预加载
// prepare for outher
type _BaseMgr struct {
*gorm.DB
@@ -26,8 +28,18 @@ func (obj *_BaseMgr) GetDB() *gorm.DB {
return obj.DB
}
// IsRelated Query foreign key Association.是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) IsRelated(b bool) {
// UpdateDB update gorm.DB info
func (obj *_BaseMgr) UpdateDB(db *gorm.DB) {
obj.DB = db
}
// GetIsRelated Query foreign key Association.获取是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) GetIsRelated() bool {
return obj.isRelated
}
// SetIsRelated Query foreign key Association.设置是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) SetIsRelated(b bool) {
obj.isRelated = b
}
@@ -45,6 +57,18 @@ type optionFunc func(*options)
func (f optionFunc) apply(o *options) {
f(o)
}
// OpenRelated 打开全局预加载
func OpenRelated() {
gloabIsRelated = true
}
// CloseRelated 关闭全局预加载
func CloseRelated() {
gloabIsRelated = true
}
`
genlogic = `{{$obj := .}}{{$list := $obj.Em}}
@@ -57,7 +81,7 @@ func {{$obj.StructName}}Mgr(db *gorm.DB) *_{{$obj.StructName}}Mgr {
if db == nil {
panic(fmt.Errorf("{{$obj.StructName}}Mgr need init by db"))
}
return &_{{$obj.StructName}}Mgr{_BaseMgr: &_BaseMgr{DB: db}}
return &_{{$obj.StructName}}Mgr{_BaseMgr: &_BaseMgr{DB: db, isRelated: gloabIsRelated}}
}
// GetTableName get sql table name.获取数据库名字
@@ -161,7 +185,7 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{$oem.Co
genPreload = `if err == nil && obj.isRelated { {{range $obj := .}}{{if $obj.IsMulti}}
{
var info []{{$obj.ForeignkeyStructName}} // {{$obj.Notes}}
err = obj.DB.Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&info).Error
err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&info).Error
if err != nil {
return
}
@@ -169,7 +193,7 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{$oem.Co
} {{else}}
{
var info {{$obj.ForeignkeyStructName}} // {{$obj.Notes}}
err = obj.DB.Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&info).Error
err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", result.{{$obj.ColStructName}}).Find(&info).Error
if err != nil {
return
}
@@ -181,7 +205,7 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{$oem.Co
for i := 0; i < len(results); i++ { {{range $obj := .}}{{if $obj.IsMulti}}
{
var info []{{$obj.ForeignkeyStructName}} // {{$obj.Notes}}
err = obj.DB.Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&info).Error
err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&info).Error
if err != nil {
return
}
@@ -189,7 +213,7 @@ func (obj *_{{$obj.StructName}}Mgr) GetBatchFrom{{$oem.ColStructName}}({{$oem.Co
} {{else}}
{
var info {{$obj.ForeignkeyStructName}} // {{$obj.Notes}}
err = obj.DB.Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&info).Error
err = obj.DB.New().Table("{{$obj.ForeignkeyTableName}}").Where("{{$obj.ForeignkeyCol}} = ?", results[i].{{$obj.ColStructName}}).Find(&info).Error
if err != nil {
return
}

View File

@@ -1,44 +0,0 @@
package genfunc
import (
"context"
"github.com/jinzhu/gorm"
)
// prepare for outher
type _BaseMgr struct {
*gorm.DB
ctx *context.Context
isRelated bool
}
// SetCtx set context
func (obj *_BaseMgr) SetCtx(c *context.Context) {
obj.ctx = c
}
// GetDB get gorm.DB info
func (obj *_BaseMgr) GetDB() *gorm.DB {
return obj.DB
}
// IsRelated Query foreign key Association.是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) IsRelated(b bool) {
obj.isRelated = b
}
type options struct {
query map[string]interface{}
}
// Option overrides behavior of Connect.
type Option interface {
apply(*options)
}
type optionFunc func(*options)
func (f optionFunc) apply(o *options) {
f(o)
}

View File

@@ -1,175 +0,0 @@
package genfunc
import (
"fmt"
"github.com/jinzhu/gorm"
)
// Example demo of root
type Example struct {
ID int `json:"-"`
UserID int `json:"userId"`
UserList []User `gorm:"association_foreignkey:userId;foreignkey:job" json:"user_list"`
}
// User demo of user
type User struct {
UserID int `json:"userId"`
Job int `json:"job"`
}
////////////////////////////////////////////-----logic------
type _ExampleMgr struct {
*_BaseMgr
}
// ExampleMgr open func
func ExampleMgr(db *gorm.DB) *_ExampleMgr {
if db == nil {
panic(fmt.Errorf("ExampleMgr need init by db"))
}
return &_ExampleMgr{_BaseMgr: &_BaseMgr{DB: db}}
}
// GetTableName get sql table name.获取数据库名字
func (obj *_ExampleMgr) GetTableName() string {
return "example"
}
// Get 获取
func (obj *_ExampleMgr) Get() (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&result).Error
if err == nil && obj.isRelated {
var info []User
err = obj.DB.Where("job = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
return
}
// Gets 获取批量结果
func (obj *_ExampleMgr) Gets() (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
var userList []User
err = obj.DB.Where("job = ?", results[i].UserID).Find(&userList).Error
if err != nil {
return
}
results[i].UserList = userList
}
}
return
}
// GetFromID 通过id获取内容
func (obj *_ExampleMgr) GetFromID(id int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", id).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
var userList []User
err = obj.DB.Where("job = ?", results[i].UserID).Find(&userList).Error
if err != nil {
return
}
results[i].UserList = userList
}
}
return
}
// GetByPrimaryKey 唯一主键查找
func (obj *_ExampleMgr) GetByPrimaryKey(id int64) (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", id).Find(&result).Error
if err == nil && obj.isRelated {
var info []User
err = obj.DB.Where("job = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
return
}
// GetByPrimaryKey 批量唯一主键查找
func (obj *_ExampleMgr) GetByPrimaryKeys(ids []int64) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", ids).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
var userList []User
err = obj.DB.Where("job = ?", results[i].UserID).Find(&userList).Error
if err != nil {
return
}
results[i].UserList = userList
}
}
return
}
//////////////////////////option case ////////////////////////////////////////////
// GetByOption 功能选项模式获取
func (obj *_ExampleMgr) GetByOption(opts ...Option) (result Example, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&result).Error
if err == nil && obj.isRelated {
var info []User
err = obj.DB.Where("job = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
return
}
// GetByPrimaryKey 批量功能选项模式获取
func (obj *_ExampleMgr) GetByOptions(opts ...Option) (results []*Example, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
var userList []User
err = obj.DB.Where("job = ?", results[i].UserID).Find(&userList).Error
if err != nil {
return
}
results[i].UserList = userList
}
}
return
}
// WithID id获取
func (obj *_ExampleMgr) WithID(id int64) Option {
return optionFunc(func(o *options) { o.query["id"] = id })
}
func (obj *_ExampleMgr) WithUserID(id int64) Option {
return optionFunc(func(o *options) {
o.query["user_id"] = id
})
}
///////////////////////////////////////////////////

View File

@@ -4,24 +4,93 @@ import (
"fmt"
"testing"
"github.com/jinzhu/gorm"
"github.com/xxjwxc/gormt/data/view/genfunc/model"
_ "github.com/go-sql-driver/mysql"
"github.com/xxjwxc/public/mysqldb"
)
func TestFunc(t *testing.T) {
orm := mysqldb.OnInitDBOrm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local")
defer orm.OnDestoryDB()
mgr := model.OrganMgr(orm.DB)
mgr.IsRelated(true) // 设置允许加载外键
res, err := mgr.GetFromUserID(2) // 通过列获取
fmt.Println(res, err)
obj1, err := mgr.GetByOptions(mgr.WithID(1), mgr.WithUserID(1)) // 批量获取
fmt.Println(obj1, err)
obj2, err := mgr.GetByOption(mgr.WithID(1), mgr.WithUserID(1)) // 多条件获取一条
fmt.Println(obj2, err)
// 复合键获取
func GetGorm(dataSourceName string) *gorm.DB {
db, err := gorm.Open("mysql", dataSourceName)
if err != nil {
panic(err)
}
db.LogMode(true)
return db
}
// TestFuncGet 测试条件获(Get/Gets)
func TestFuncGet(t *testing.T) {
model.OpenRelated() // 打开全局预加载 (外键)
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
accountMgr := model.AccountMgr(db.Where("account_id = ?", 2))
account, err := accountMgr.Get() // 单条获取
fmt.Println(err)
fmt.Println(account)
dbs := db.Where("name = ?", "bbbb")
accounts, err := model.AccountMgr(dbs).Gets() // 多个获取
fmt.Println(err)
fmt.Println(accounts)
}
// TestFuncOption 功能选项方式获取
func TestFuncOption(t *testing.T) {
// db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
// defer db.Close()
orm := mysqldb.OnInitDBOrm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True") // 推荐方式
defer orm.OnDestoryDB()
db := orm.DB
accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
account, err := accountMgr.GetByOption(accountMgr.WithID(1), accountMgr.WithUserID(1)) // 多case条件获取单个
fmt.Println(err)
fmt.Println(account)
accounts, err := accountMgr.GetByOptions(accountMgr.WithName("bbbb")) // 多功能选项获取
fmt.Println(err)
fmt.Println(accounts)
}
// TestFuncFrom 单元素方式获取
func TestFuncFrom(t *testing.T) {
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
account, err := accountMgr.GetFromAccountID(2)
fmt.Println(err)
fmt.Println(account)
accounts, err := accountMgr.GetFromName("bbbb")
fmt.Println(err)
fmt.Println(accounts)
}
// TestFuncFetchBy 索引方式获取
func TestFuncFetchBy(t *testing.T) {
db := GetGorm("root:qwer@tcp(127.0.0.1:3306)/matrix?charset=utf8&parseTime=True&loc=Local&interpolateParams=True")
defer db.Close()
accountMgr := model.AccountMgr(db)
accountMgr.SetIsRelated(true) // 打开预加载 (外键)
account, err := accountMgr.FetchByPrimaryKey(2) // primay key
fmt.Println(err)
fmt.Println(account)
account1, err := accountMgr.FetchByAccountUniqueIndex(2, 2) // unique index
fmt.Println(err)
fmt.Println(account1)
accounts, err := accountMgr.FetchByTpIndex(2, 2)
fmt.Println(err)
fmt.Println(accounts)
}

View File

@@ -6,6 +6,8 @@ import (
"github.com/jinzhu/gorm"
)
var gloabIsRelated bool // 全局预加载
// prepare for outher
type _BaseMgr struct {
*gorm.DB
@@ -23,8 +25,18 @@ func (obj *_BaseMgr) GetDB() *gorm.DB {
return obj.DB
}
// IsRelated Query foreign key Association.是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) IsRelated(b bool) {
// UpdateDB update gorm.DB info
func (obj *_BaseMgr) UpdateDB(db *gorm.DB) {
obj.DB = db
}
// GetIsRelated Query foreign key Association.获取是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) GetIsRelated() bool {
return obj.isRelated
}
// SetIsRelated Query foreign key Association.设置是否查询外键关联(gorm.Related)
func (obj *_BaseMgr) SetIsRelated(b bool) {
obj.isRelated = b
}
@@ -42,3 +54,13 @@ type optionFunc func(*options)
func (f optionFunc) apply(o *options) {
f(o)
}
// OpenRelated 打开全局预加载
func OpenRelated() {
gloabIsRelated = true
}
// CloseRelated 关闭全局预加载
func CloseRelated() {
gloabIsRelated = true
}

View File

@@ -0,0 +1,369 @@
package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
type _AccountMgr struct {
*_BaseMgr
}
// AccountMgr open func
func AccountMgr(db *gorm.DB) *_AccountMgr {
if db == nil {
panic(fmt.Errorf("AccountMgr need init by db"))
}
return &_AccountMgr{_BaseMgr: &_BaseMgr{DB: db, isRelated: gloabIsRelated}}
}
// GetTableName get sql table name.获取数据库名字
func (obj *_AccountMgr) GetTableName() string {
return "account"
}
// Get 获取
func (obj *_AccountMgr) Get() (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// Gets 获取批量结果
func (obj *_AccountMgr) Gets() (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
//////////////////////////option case ////////////////////////////////////////////
// WithID id获取
func (obj *_AccountMgr) WithID(ID int) Option {
return optionFunc(func(o *options) { o.query["id"] = ID })
}
// WithAccountID account_id获取
func (obj *_AccountMgr) WithAccountID(AccountID int) Option {
return optionFunc(func(o *options) { o.query["account_id"] = AccountID })
}
// WithUserID user_id获取
func (obj *_AccountMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
}
// WithType type获取
func (obj *_AccountMgr) WithType(Type int) Option {
return optionFunc(func(o *options) { o.query["type"] = Type })
}
// WithName name获取
func (obj *_AccountMgr) WithName(Name string) Option {
return optionFunc(func(o *options) { o.query["name"] = Name })
}
// GetByOption 功能选项模式获取
func (obj *_AccountMgr) GetByOption(opts ...Option) (result Account, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// GetByOptions 批量功能选项模式获取
func (obj *_AccountMgr) GetByOptions(opts ...Option) (results []*Account, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
//////////////////////////enume case ////////////////////////////////////////////
// GetFromID 通过id获取内容
func (obj *_AccountMgr) GetFromID(ID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// GetBatchFromID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromID(IDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", IDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetFromAccountID 通过account_id获取内容
func (obj *_AccountMgr) GetFromAccountID(AccountID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ?", AccountID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// GetBatchFromAccountID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromAccountID(AccountIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id IN (?)", AccountIDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetFromUserID 通过user_id获取内容
func (obj *_AccountMgr) GetFromUserID(UserID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromUserID(UserIDs []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetFromType 通过type获取内容
func (obj *_AccountMgr) GetFromType(Type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type = ?", Type).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetBatchFromType 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromType(Types []int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type IN (?)", Types).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetFromName 通过name获取内容
func (obj *_AccountMgr) GetFromName(Name string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", Name).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
// GetBatchFromName 批量唯一主键查找
func (obj *_AccountMgr) GetBatchFromName(Names []string) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", Names).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}
//////////////////////////primary index case ////////////////////////////////////////////
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_AccountMgr) FetchByPrimaryKey(ID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// FetchByAccountUniqueIndex primay or index 获取唯一内容
func (obj *_AccountMgr) FetchByAccountUniqueIndex(AccountID int, UserID int) (result Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("account_id = ? AND user_id = ?", AccountID, UserID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.User = info
}
}
return
}
// FetchByTpIndex 获取多个内容
func (obj *_AccountMgr) FetchByTpIndex(UserID int, Type int) (results []*Account, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ? AND type = ?", UserID, Type).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info User //
err = obj.DB.New().Table("user").Where("user_id = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].User = info
}
}
}
return
}

View File

@@ -1,181 +0,0 @@
package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
type _ExampleMgr struct {
*_BaseMgr
}
// ExampleMgr open func
func ExampleMgr(db *gorm.DB) *_ExampleMgr {
if db == nil {
panic(fmt.Errorf("ExampleMgr need init by db"))
}
return &_ExampleMgr{_BaseMgr: &_BaseMgr{DB: db}}
}
// GetTableName get sql table name.获取数据库名字
func (obj *_ExampleMgr) GetTableName() string {
return "example"
}
// Get 获取
func (obj *_ExampleMgr) Get() (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&result).Error
return
}
// Gets 获取批量结果
func (obj *_ExampleMgr) Gets() (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&results).Error
return
}
//////////////////////////option case ////////////////////////////////////////////
// WithUserID user_id获取
func (obj *_ExampleMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
}
// WithName name获取
func (obj *_ExampleMgr) WithName(Name string) Option {
return optionFunc(func(o *options) { o.query["name"] = Name })
}
// WithSex sex获取
func (obj *_ExampleMgr) WithSex(Sex int) Option {
return optionFunc(func(o *options) { o.query["sex"] = Sex })
}
// WithJob job获取
func (obj *_ExampleMgr) WithJob(Job int) Option {
return optionFunc(func(o *options) { o.query["job"] = Job })
}
// WithID id获取
func (obj *_ExampleMgr) WithID(ID int) Option {
return optionFunc(func(o *options) { o.query["id"] = ID })
}
// GetByOption 功能选项模式获取
func (obj *_ExampleMgr) GetByOption(opts ...Option) (result Example, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&result).Error
return
}
// GetByOptions 批量功能选项模式获取
func (obj *_ExampleMgr) GetByOptions(opts ...Option) (results []*Example, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&results).Error
return
}
//////////////////////////enume case ////////////////////////////////////////////
// GetFromUserID 通过user_id获取内容
func (obj *_ExampleMgr) GetFromUserID(UserID int) (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_ExampleMgr) GetBatchFromUserID(UserIDs []int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
return
}
// GetFromName 通过name获取内容
func (obj *_ExampleMgr) GetFromName(Name string) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name = ?", Name).Find(&results).Error
return
}
// GetBatchFromName 批量唯一主键查找
func (obj *_ExampleMgr) GetBatchFromName(Names []string) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("name IN (?)", Names).Find(&results).Error
return
}
// GetFromSex 通过sex获取内容
func (obj *_ExampleMgr) GetFromSex(Sex int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex = ?", Sex).Find(&results).Error
return
}
// GetBatchFromSex 批量唯一主键查找
func (obj *_ExampleMgr) GetBatchFromSex(Sexs []int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex IN (?)", Sexs).Find(&results).Error
return
}
// GetFromJob 通过job获取内容
func (obj *_ExampleMgr) GetFromJob(Job int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job = ?", Job).Find(&results).Error
return
}
// GetBatchFromJob 批量唯一主键查找
func (obj *_ExampleMgr) GetBatchFromJob(Jobs []int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("job IN (?)", Jobs).Find(&results).Error
return
}
// GetFromID 通过id获取内容
func (obj *_ExampleMgr) GetFromID(ID int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&results).Error
return
}
// GetBatchFromID 批量唯一主键查找
func (obj *_ExampleMgr) GetBatchFromID(IDs []int) (results []*Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", IDs).Find(&results).Error
return
}
//////////////////////////primary index case ////////////////////////////////////////////
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_ExampleMgr) FetchByPrimaryKey(UserID int) (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
return
}
// FetchByIndex primay or index 获取唯一内容
func (obj *_ExampleMgr) FetchByIndex(Sex int) (result Example, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex = ?", Sex).Find(&result).Error
return
}

View File

@@ -1,312 +0,0 @@
package model
import (
"fmt"
"github.com/jinzhu/gorm"
)
type _OrganMgr struct {
*_BaseMgr
}
// OrganMgr open func
func OrganMgr(db *gorm.DB) *_OrganMgr {
if db == nil {
panic(fmt.Errorf("OrganMgr need init by db"))
}
return &_OrganMgr{_BaseMgr: &_BaseMgr{DB: db}}
}
// GetTableName get sql table name.获取数据库名字
func (obj *_OrganMgr) GetTableName() string {
return "organ"
}
// Get 获取
func (obj *_OrganMgr) Get() (result Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&result).Error
if err == nil && obj.isRelated {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
}
return
}
// Gets 获取批量结果
func (obj *_OrganMgr) Gets() (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
//////////////////////////option case ////////////////////////////////////////////
// WithID id获取
func (obj *_OrganMgr) WithID(ID int) Option {
return optionFunc(func(o *options) { o.query["id"] = ID })
}
// WithUserID user_id获取
func (obj *_OrganMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
}
// WithType type获取
func (obj *_OrganMgr) WithType(Type int) Option {
return optionFunc(func(o *options) { o.query["type"] = Type })
}
// WithScore score获取
func (obj *_OrganMgr) WithScore(Score int) Option {
return optionFunc(func(o *options) { o.query["score"] = Score })
}
// GetByOption 功能选项模式获取
func (obj *_OrganMgr) GetByOption(opts ...Option) (result Organ, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&result).Error
if err == nil && obj.isRelated {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
}
return
}
// GetByOptions 批量功能选项模式获取
func (obj *_OrganMgr) GetByOptions(opts ...Option) (results []*Organ, err error) {
options := options{
query: make(map[string]interface{}, len(opts)),
}
for _, o := range opts {
o.apply(&options)
}
err = obj.DB.Table(obj.GetTableName()).Where(options.query).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
//////////////////////////enume case ////////////////////////////////////////////
// GetFromID 通过id获取内容
func (obj *_OrganMgr) GetFromID(ID int) (result Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
}
return
}
// GetBatchFromID 批量唯一主键查找
func (obj *_OrganMgr) GetBatchFromID(IDs []int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id IN (?)", IDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetFromUserID 通过user_id获取内容
func (obj *_OrganMgr) GetFromUserID(UserID int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_OrganMgr) GetBatchFromUserID(UserIDs []int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetFromType 通过type获取内容
func (obj *_OrganMgr) GetFromType(Type int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type = ?", Type).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetBatchFromType 批量唯一主键查找
func (obj *_OrganMgr) GetBatchFromType(Types []int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("type IN (?)", Types).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetFromScore 通过score获取内容
func (obj *_OrganMgr) GetFromScore(Score int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("score = ?", Score).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
// GetBatchFromScore 批量唯一主键查找
func (obj *_OrganMgr) GetBatchFromScore(Scores []int) (results []*Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("score IN (?)", Scores).Find(&results).Error
if err == nil && obj.isRelated {
for i := 0; i < len(results); i++ {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", results[i].UserID).Find(&info).Error
if err != nil {
return
}
results[i].UserList = info
}
}
}
return
}
//////////////////////////primary index case ////////////////////////////////////////////
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_OrganMgr) FetchByPrimaryKey(ID int) (result Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("id = ?", ID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
}
return
}
// FetchByIndex primay or index 获取唯一内容
func (obj *_OrganMgr) FetchByIndex(UserID int) (result Organ, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
if err == nil && obj.isRelated {
{
var info []User //
err = obj.DB.Table("user").Where("sex = ?", result.UserID).Find(&info).Error
if err != nil {
return
}
result.UserList = info
}
}
return
}

View File

@@ -15,7 +15,7 @@ func UserMgr(db *gorm.DB) *_UserMgr {
if db == nil {
panic(fmt.Errorf("UserMgr need init by db"))
}
return &_UserMgr{_BaseMgr: &_BaseMgr{DB: db}}
return &_UserMgr{_BaseMgr: &_BaseMgr{DB: db, isRelated: gloabIsRelated}}
}
// GetTableName get sql table name.获取数据库名字
@@ -39,9 +39,9 @@ func (obj *_UserMgr) Gets() (results []*User, err error) {
//////////////////////////option case ////////////////////////////////////////////
// WithUserID userId获取
// WithUserID user_id获取
func (obj *_UserMgr) WithUserID(UserID int) Option {
return optionFunc(func(o *options) { o.query["userId"] = UserID })
return optionFunc(func(o *options) { o.query["user_id"] = UserID })
}
// WithName name获取
@@ -89,16 +89,16 @@ func (obj *_UserMgr) GetByOptions(opts ...Option) (results []*User, err error) {
//////////////////////////enume case ////////////////////////////////////////////
// GetFromUserID 通过userId获取内容
// GetFromUserID 通过user_id获取内容
func (obj *_UserMgr) GetFromUserID(UserID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("userId = ?", UserID).Find(&result).Error
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
return
}
// GetBatchFromUserID 批量唯一主键查找
func (obj *_UserMgr) GetBatchFromUserID(UserIDs []int) (results []*User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("userId IN (?)", UserIDs).Find(&results).Error
err = obj.DB.Table(obj.GetTableName()).Where("user_id IN (?)", UserIDs).Find(&results).Error
return
}
@@ -149,14 +149,7 @@ func (obj *_UserMgr) GetBatchFromJob(Jobs []int) (results []*User, err error) {
// FetchByPrimaryKey primay or index 获取唯一内容
func (obj *_UserMgr) FetchByPrimaryKey(UserID int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("userId = ?", UserID).Find(&result).Error
return
}
// FetchByIndex primay or index 获取唯一内容
func (obj *_UserMgr) FetchByIndex(Sex int) (result User, err error) {
err = obj.DB.Table(obj.GetTableName()).Where("sex = ?", Sex).Find(&result).Error
err = obj.DB.Table(obj.GetTableName()).Where("user_id = ?", UserID).Find(&result).Error
return
}

View File

@@ -1,27 +1,19 @@
package model
// Example [...]
type Example struct {
UserID int `gorm:"primary_key" json:"user_id"`
Name string `json:"name"`
Sex int `gorm:"index" json:"sex"`
Job int `json:"job"`
ID int `json:"-"`
}
// Organ [...]
type Organ struct {
ID int `gorm:"primary_key" json:"-"`
UserID int `gorm:"index" json:"user_id"`
UserList []User `gorm:"association_foreignkey:user_id;foreignkey:sex" json:"user_list"`
Type int `json:"type"`
Score int `json:"score"`
// Account [...]
type Account struct {
ID int `gorm:"primary_key;column:id;type:int(11);not null" json:"-"`
AccountID int `gorm:"unique_index:account;column:account_id;type:int(11)" json:"account_id"`
UserID int `gorm:"unique_index:account;index:tp;column:user_id;type:int(11)" json:"user_id"`
User User `gorm:"association_foreignkey:user_id;foreignkey:user_id" json:"user_list"`
Type int `gorm:"index:tp;column:type;type:int(11)" json:"type"`
Name string `gorm:"column:name;type:varchar(255)" json:"name"`
}
// User [...]
type User struct {
UserID int `gorm:"primary_key" json:"user_id"`
Name string `json:"name"`
Sex int `gorm:"index" json:"sex"`
Job int `json:"job"`
UserID int `gorm:"primary_key;column:user_id;type:int(11);not null" json:"user_id"`
Name string `gorm:"column:name;type:varchar(30);not null" json:"name"`
Sex int `gorm:"column:sex;type:int(11);not null" json:"sex"`
Job int `gorm:"column:job;type:int(11);not null" json:"job"`
}

View File

@@ -0,0 +1,66 @@
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MySQL
Source Server Version : 80017
Source Host : localhost:3306
Source Schema : matrix
Target Server Type : MySQL
Target Server Version : 80017
File Encoding : 65001
Date: 12/01/2020 21:35:09
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for account
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`account_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
`type` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `account` (`account_id`,`user_id`),
KEY `tp` (`user_id`,`type`),
CONSTRAINT `account_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of account
-- ----------------------------
BEGIN;
INSERT INTO `account` VALUES (1, 1, 1, 1, 'aaaa');
INSERT INTO `account` VALUES (2, 2, 2, 2, 'bbbb');
INSERT INTO `account` VALUES (3, 3, 2, 2, 'bbbb');
COMMIT;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`sex` int(11) NOT NULL,
`job` int(11) NOT NULL,
PRIMARY KEY (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
BEGIN;
INSERT INTO `user` VALUES (1, 'xxj1', 1, 1);
INSERT INTO `user` VALUES (2, 'xxj2', 2, 2);
INSERT INTO `user` VALUES (3, 'xxj3', 3, 3);
COMMIT;
SET FOREIGN_KEY_CHECKS = 1;

View File

@@ -234,10 +234,10 @@ func (m *_Model) generateFunc() (genOut []GenOutInfo) {
isMulti = false
buildFList(&unique, ColumusKeyUnique, "", typeName, el.Name)
case ColumusKeyIndex: // index key.复合索引
buildFList(&uniqueIndex, ColumusKeyIndex, v1.KeyName, typeName, el.Name)
buildFList(&index, ColumusKeyIndex, v1.KeyName, typeName, el.Name)
case ColumusKeyUniqueIndex: // unique index key.唯一复合索引
isMulti = false
buildFList(&index, ColumusKeyUniqueIndex, v1.KeyName, typeName, el.Name)
buildFList(&uniqueIndex, ColumusKeyUniqueIndex, v1.KeyName, typeName, el.Name)
}
}