Files
jx-callback/business/model/dao/dao.go
2018-09-02 19:11:54 +08:00

74 lines
1.8 KiB
Go

package dao
import (
"fmt"
"reflect"
"git.rosy.net.cn/baseapi/utils"
"git.rosy.net.cn/jx-callback/business/model"
"git.rosy.net.cn/jx-callback/globals/gormdb"
"github.com/jinzhu/gorm"
)
func GetRows(db *gorm.DB, inPtr interface{}, sql string, values ...interface{}) (err error) {
if db == nil {
db = gormdb.GetDB()
}
topTypeInfo := reflect.TypeOf(inPtr)
if topTypeInfo.Kind() != reflect.Ptr {
panic("SelectEntities inPtr should be slice ptr (*[]Type)")
}
typeInfo := topTypeInfo.Elem()
if typeInfo.Kind() != reflect.Slice {
fmt.Printf("type:%s", typeInfo.String())
panic("SelectEntities inPtr should be slice ptr (*[]Type)")
}
elmType := typeInfo.Elem()
valueInfo := reflect.ValueOf(inPtr)
rows, err := db.Raw(sql, values...).Rows()
if err == nil {
defer rows.Close()
for rows.Next() {
var value reflect.Value
if elmType.Kind() == reflect.Ptr {
value = reflect.New(elmType.Elem())
} else {
value = reflect.New(elmType)
}
db.ScanRows(rows, value.Interface())
if elmType.Kind() != reflect.Ptr {
value = value.Elem()
}
valueInfo.Elem().Set(reflect.Append(valueInfo.Elem(), value))
}
return nil
}
return err
}
func GetEntity(item interface{}, db *gorm.DB) error {
if db == nil {
db = gormdb.GetDB()
}
err := utils.CallFuncLogError(func() error {
return db.First(item).Error
}, reflect.TypeOf(item).Name())
return err
}
func GetSellCities(skuNameID int, vendorID int, db *gorm.DB) (cities []*model.Place, err error) {
cities = []*model.Place{}
sql := `
SELECT DISTINCT t3.*
FROM sku_name_place_bind t1
JOIN place t2 ON t1.place_code = t2.code
JOIN place t3 ON (t2.level = 2 AND t2.code = t3.code) OR (t2.level = 1 AND t2.code = t3.parent_code)
WHERE t1.sku_name_id = ?
`
if vendorID == model.VendorIDJD {
sql += "AND t3.jd_code <> 0\n"
}
return cities, GetRows(nil, &cities, sql, skuNameID)
}