新增模型与CMS

This commit is contained in:
yxh
2020-09-07 16:49:47 +08:00
parent ef51647959
commit 289cf4d2ac
47 changed files with 6243 additions and 122 deletions
@@ -26,6 +26,7 @@ type ReqSearchList struct {
//添加请求参数
type ReqAdd struct {
ParentId int64 `p:"parent_id" v:"integer|min:0#父级ID不能为空|父级ID必须为大于等于0的整数"`
ModelId uint `p:"model_id" v:"integer|min:1#模型ID必须为数字|模型ID不能为空"`
Name string `p:"name" v:"required#栏目名称不能为空"`
Alias string `p:"alias"`
CateType uint `p:"cate_type" v:"required|in:1,2,3,4#请选择栏目类型|栏目类型只能在1-4之间"`
@@ -69,6 +70,7 @@ func GetList() (list []*Entity, err error) {
func AddSave(req *ReqAdd) (id int64, err error) {
var entity Entity
entity.ParentId = req.ParentId
entity.ModelId = req.ModelId
entity.CateType = req.CateType
entity.Status = req.Status
entity.Name = req.Name
@@ -128,6 +130,7 @@ func EditSave(req *ReqEdit) (id int64, err error) {
}
entity.Id = gconv.Uint64(req.Id)
entity.ParentId = req.ParentId
entity.ModelId = req.ModelId
entity.CateType = req.CateType
entity.Status = req.Status
entity.Name = req.Name
@@ -13,6 +13,7 @@ import (
type Entity struct {
Id uint64 `orm:"id,primary" json:"id"` // 分类id
ParentId int64 `orm:"parent_id" json:"parent_id"` // 分类父id
ModelId uint `orm:"model_id" json:"model_id"` // 模型id
Status uint `orm:"status" json:"status"` // 状态,1:发布,0:不发布
DeleteTime uint `orm:"delete_time" json:"delete_time"` // 删除时间
ListOrder float64 `orm:"list_order" json:"list_order"` // 排序
+20 -39
View File
@@ -20,19 +20,17 @@ import (
//添加文章参数
type ReqAddParams struct {
NewsStatus uint `p:"status" v:"in:0,1#状态只能为0或1"` // 状态;1:已发布;0:未发布;
//IsTop uint `p:"IsTop" v:"in:0,1#置顶只能为0或1"` // 是否置顶;1:置顶;0:不置顶
//Recommended uint `p:"recommended" v:"in:0,1#推荐只能为0或1"` // 是否推荐;1:推荐;0:不推荐
NewsStatus uint `p:"status" v:"in:0,1#状态只能为0或1"` // 状态;1:已发布;0:未发布;
Attr []int `p:attr` //文章标记 置顶 推荐
PublishedTime string `p:"published_time"` // 发布时间
NewsTitle string `p:"title" v:"required#标题不能为空"` // post标题
NewsKeywords string `p:"keywords"` // seo keywords
NewsExcerpt string `p:"excerpt"` // post摘要
NewsSource string `p:"source" ` // 转载文章的来源
NewsContent string `p:"content" v:"required-if:IsJump,0#文章内容不能为空"` // 文章内容
Thumbnail string `p:"thumbnail" ` // 缩略图
IsJump uint `p:"IsJump" v:"in:0,1#跳转类型只能为0或1"` // 是否跳转地址
JumpUrl string `p:"JumpUrl" v:"required-if:IsJump,1|url#跳转地址不能为空|跳转地址格式不正确"` // 跳转地址
ModelForm g.Map `p:"modelForm"`
}
//文章搜索参数
@@ -51,17 +49,12 @@ type ReqEditParams struct {
}
//添加文章操作
func AddNews(req *ReqAddParams, cateIds []int, userId int) (insId int64, err error) {
func AddNews(req *ReqAddParams, cateIds []int, userId int, tx *gdb.TX) (insId int64, err error) {
if len(cateIds) == 0 {
err = gerror.New("栏目不能为空")
return
}
tx, err := g.DB().Begin()
if err != nil {
g.Log().Error(err)
err = gerror.New("添加失败")
return
}
nowTime := gconv.Uint(gtime.Timestamp())
entity := &Entity{
UserId: gconv.Uint64(userId),
@@ -73,7 +66,6 @@ func AddNews(req *ReqAddParams, cateIds []int, userId int) (insId int64, err err
NewsKeywords: req.NewsKeywords,
NewsExcerpt: req.NewsExcerpt,
NewsSource: req.NewsSource,
NewsContent: req.NewsContent,
Thumbnail: req.Thumbnail,
IsJump: req.IsJump,
JumpUrl: req.JumpUrl,
@@ -85,18 +77,16 @@ func AddNews(req *ReqAddParams, cateIds []int, userId int) (insId int64, err err
entity.Recommended = 1
}
}
res, e := entity.Save()
res, e := Model.TX(tx).Insert(entity)
if e != nil {
g.Log().Error(e)
err = gerror.New("添加文章失败")
tx.Rollback()
err = gerror.New("保存文章失败")
return
}
insId, err = res.LastInsertId()
if err != nil {
g.Log().Error(err)
err = gerror.New("添加文章失败")
tx.Rollback()
return
}
//保存栏目与文章关联信息
@@ -105,29 +95,21 @@ func AddNews(req *ReqAddParams, cateIds []int, userId int) (insId int64, err err
catNewsEntity[k].CategoryId = gconv.Uint64(cateId)
catNewsEntity[k].NewsId = gconv.Uint64(insId)
}
_, err = cms_category_news.Model.Data(catNewsEntity).Insert()
_, err = cms_category_news.Model.TX(tx).Data(catNewsEntity).Insert()
if err != nil {
g.Log().Error(err)
err = gerror.New("添加文章失败")
tx.Rollback()
err = gerror.New("设置文章栏目失败")
return
}
tx.Commit()
return
}
//修改文章操作
func EditNews(req *ReqEditParams, cateIds []int) (err error) {
func EditNews(req *ReqEditParams, cateIds []int, tx *gdb.TX) (err error) {
if len(cateIds) == 0 {
err = gerror.New("栏目不能为空")
return
}
tx, err := g.DB().Begin()
if err != nil {
g.Log().Error(err)
err = gerror.New("添加失败")
return
}
entity, err := Model.FindOne("id", req.Id)
if err != nil {
g.Log().Error(err)
@@ -143,7 +125,6 @@ func EditNews(req *ReqEditParams, cateIds []int) (err error) {
entity.NewsKeywords = req.NewsKeywords
entity.NewsExcerpt = req.NewsExcerpt
entity.NewsSource = req.NewsSource
entity.NewsContent = req.NewsContent
entity.Thumbnail = req.Thumbnail
entity.IsJump = req.IsJump
entity.JumpUrl = req.JumpUrl
@@ -154,11 +135,10 @@ func EditNews(req *ReqEditParams, cateIds []int) (err error) {
entity.Recommended = 1
}
}
_, err = entity.Update()
_, err = Model.TX(tx).Replace(entity)
if err != nil {
g.Log().Error(err)
err = gerror.New("修改文章失败")
tx.Rollback()
return
}
//删除旧的栏目文章关联信息
@@ -167,11 +147,10 @@ func EditNews(req *ReqEditParams, cateIds []int) (err error) {
return
}
for _, cn := range cnList {
_, err = cn.Delete()
_, err = cms_category_news.Model.TX(tx).Delete("news_id", cn.NewsId)
if err != nil {
g.Log().Error(err)
err = gerror.New("更新文章栏目所属信息失败")
tx.Rollback()
return
}
}
@@ -181,14 +160,12 @@ func EditNews(req *ReqEditParams, cateIds []int) (err error) {
catNewsEntity[k].CategoryId = gconv.Uint64(cateId)
catNewsEntity[k].NewsId = gconv.Uint64(req.Id)
}
_, err = cms_category_news.Model.Data(catNewsEntity).Insert()
_, err = cms_category_news.Model.TX(tx).Data(catNewsEntity).Insert()
if err != nil {
g.Log().Error(err)
err = gerror.New("更新文章栏目所属信息失败")
tx.Rollback()
return
}
tx.Commit()
return
}
@@ -247,12 +224,16 @@ func GetById(id int) (news *Entity, err error) {
return
}
func DeleteByIds(ids []int) error {
_, err := Model.Delete("id in (?)", ids)
func DeleteByIds(ids []int, tx *gdb.TX) error {
_, err := Model.TX(tx).Delete("id in (?)", ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除失败")
return gerror.New("删除文章失败")
}
_, err = cms_category_news.Model.TX(tx).Delete("news_id in (?)", ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除文章栏目关联信息失败")
}
cms_category_news.Delete("news_id in (?)", ids)
return nil
}
@@ -12,7 +12,6 @@ import (
// Entity is the golang structure for table cms_news.
type Entity struct {
Id uint64 `orm:"id,primary" json:"id"` //
NewsFormat uint `orm:"news_format" json:"news_format"` // 内容格式;1:html;2:md
UserId uint64 `orm:"user_id" json:"user_id"` // 发表者用户id
NewsStatus uint `orm:"news_status" json:"news_status"` // 状态;1:已发布;0:未发布;
IsTop uint `orm:"is_top" json:"is_top"` // 是否置顶;1:置顶;0:不置顶
@@ -27,11 +26,9 @@ type Entity struct {
NewsKeywords string `orm:"news_keywords" json:"news_keywords"` // seo keywords
NewsExcerpt string `orm:"news_excerpt" json:"news_excerpt"` // post摘要
NewsSource string `orm:"news_source" json:"news_source"` // 转载文章的来源
NewsContent string `orm:"news_content" json:"news_content"` // 文章内容
Thumbnail string `orm:"thumbnail" json:"thumbnail"` // 缩略图
IsJump uint `orm:"is_jump" json:"is_jump"` // 是否跳转地址
JumpUrl string `orm:"jump_url" json:"jump_url"` // 跳转地址
IsPushed uint `orm:"is_pushed" json:"is_pushed"` // 是否已推送
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
@@ -25,7 +25,6 @@ var (
// Columns defines and stores column names for table cms_news.
Columns = struct {
Id string //
NewsFormat string // 内容格式;1:html;2:md
UserId string // 发表者用户id
NewsStatus string // 状态;1:已发布;0:未发布;
IsTop string // 是否置顶;1:置顶;0:不置顶
@@ -40,14 +39,11 @@ var (
NewsKeywords string // seo keywords
NewsExcerpt string // post摘要
NewsSource string // 转载文章的来源
NewsContent string // 文章内容
Thumbnail string // 缩略图
IsJump string // 是否跳转地址
JumpUrl string // 跳转地址
IsPushed string // 是否已推送
}{
Id: "id",
NewsFormat: "news_format",
UserId: "user_id",
NewsStatus: "news_status",
IsTop: "is_top",
@@ -62,11 +58,9 @@ var (
NewsKeywords: "news_keywords",
NewsExcerpt: "news_excerpt",
NewsSource: "news_source",
NewsContent: "news_content",
Thumbnail: "thumbnail",
IsJump: "is_jump",
JumpUrl: "jump_url",
IsPushed: "is_pushed",
}
)
@@ -124,3 +124,13 @@ func DeleteByIds(ids []int) error {
}
return nil
}
func GetCategoryAll() (entity []*Entity, err error) {
entity, err = Model.Where(Columns.CStatus, 1).Order(Columns.CSort + " ASC," + Columns.CId + " ASC").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("获取模型分类数据失败")
return
}
return
}
@@ -0,0 +1,222 @@
// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================
package model_fields
import (
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/text/gstr"
"github.com/gogf/gf/util/gconv"
)
// AddReq 用于存储新增请求的请求参数
type AddReq struct {
ModelId uint `p:"modelId" `
FieldName string `p:"fieldName" v:"required#字段名称不能为空"`
FieldTitle string `p:"fieldTitle" `
FieldType string `p:"fieldType" `
FieldLength string `p:"fieldLength" `
FieldDefault string `p:"fieldDefault" `
FieldData string `p:"fieldData" `
FieldDesc string `p:"fieldDesc" `
FieldRules []string `p:"fieldRules" `
CreateBy uint64
FieldWidth string `p:"fieldWidth"`
fieldAlign string `p:"fieldAlign"`
}
// EditReq 用于存储修改请求参数
type EditReq struct {
FieldId int64 `p:"fieldId" v:"required#主键ID不能为空"`
ModelId uint `p:"modelId" `
FieldName string `p:"fieldName" v:"required#字段名称不能为空"`
FieldTitle string `p:"fieldTitle" `
FieldType string `p:"fieldType" `
FieldLength string `p:"fieldLength" `
FieldDefault string `p:"fieldDefault" `
FieldData string `p:"fieldData" `
FieldDesc string `p:"fieldDesc" `
FieldRules []string `p:"fieldRules" `
UpdateBy uint64
FieldWidth string `p:"fieldWidth"`
fieldAlign string `p:"fieldAlign"`
}
type RemoveReq struct {
Ids []int `p:"ids"` //删除id
}
type FieldInfo struct {
FieldId uint64 `p:"field_id,primary" json:"field_id"` // 模型字段ID
ModelId uint `p:"model_id" json:"model_id"` // 模型ID
FieldName string `p:"field_name" json:"field_name"` // 字段名称
FieldTitle string `p:"field_title" json:"field_title"` // 字段标题
FieldType string `p:"field_type" json:"field_type"` // 字段类型
FieldLength string `p:"field_length" json:"field_length"` // 字段长度
FieldDefault string `p:"field_default" json:"field_default"` // 字段默认值
FieldData string `p:"field_data" json:"field_data"` // 字段数据
FieldDesc string `p:"field_desc" json:"field_desc"` // 字段描述
FieldRules string `p:"field_rules" json:"field_rules"` // 字段规则
FieldSort int64 `p:"field_sort" json:"field_sort"` // 字段排序
CreateBy uint64 `p:"create_by" json:"create_by"` // 创建人
UpdateBy uint64 `p:"update_by" json:"update_by"` // 修改人
CreateTime uint64 `p:"create_time" json:"create_time"` // 创建时间
UpdateTime uint64 `p:"update_time" json:"update_time"` // 修改时间
ModelEdit string `p:"model_edit" json:"model_edit"`
ModelIndexes string `p:"model_indexes" json:"model_indexes"`
ModelList string `p:"model_list" json:"model_list"`
ModelOrder string `p:"model_order" json:"model_order"`
ModelPk string `p:"model_pk" json:"model_pk"`
ModelSort string `p:"model_sort" json:"model_sort"`
SearchList string `p:"search_list" json:"search_list"`
}
type SetFieldsAttrReq struct {
ModelId int `p:"modelId" json:"model_id"`
PkId uint64 `p:"pkId" json:"pk_id"`
FieldsList []FieldInfo
}
// SelectPageReq 用于存储分页查询的请求参数
type SelectPageReq struct {
ModelId int64 `p:"modelId"` //模型ID
BeginTime string `p:"beginTime"` //开始时间
EndTime string `p:"endTime"` //结束时间
PageNum int64 `p:"pageNum"` //当前页码
PageSize int `p:"pageSize"` //每页数
}
// 根据ID查询记录
func GetByID(id int64) (*Entity, error) {
entity, err := Model.FindOne(id)
if err != nil {
g.Log().Error(err)
err = gerror.New("根据ID查询记录出错")
}
if entity == nil {
err = gerror.New("没有查询到对应模型的字段")
}
return entity, nil
}
// AddSave 添加
func AddSave(req *AddReq) error {
if err := Exists(req.FieldName, req.ModelId, 0); err != nil {
return err
}
entity := new(Entity)
entity.ModelId = req.ModelId
entity.FieldName = req.FieldName
entity.FieldTitle = req.FieldTitle
entity.FieldType = req.FieldType
entity.FieldLength = req.FieldLength
entity.FieldDefault = req.FieldDefault
entity.FieldData = req.FieldData
entity.FieldDesc = req.FieldDesc
entity.FieldRules = gstr.Join(req.FieldRules, ",")
entity.CreateBy = req.CreateBy
entity.FieldSort = 1000
entity.FieldWidth = req.FieldWidth
entity.FieldAlign = req.fieldAlign
time := gconv.Uint64(gtime.Timestamp())
entity.CreateTime = time
entity.UpdateTime = time
result, err := entity.Insert()
if err != nil {
return err
}
_, err = result.LastInsertId()
if err != nil {
return err
}
return nil
}
//判断字段是否存在
func Exists(name string, modelId, fieldsId uint) error {
model := Model.Where(Columns.FieldName, name).And(Columns.ModelId, modelId)
if fieldsId != 0 {
model = model.And(Columns.FieldId, fieldsId)
}
entity, err := model.FindOne()
if err != nil {
g.Log().Error(err)
return gerror.New("判断数据重复时出错")
}
if entity != nil {
return gerror.New("已存在相同名称的字段")
}
return nil
}
// 删除
func DeleteByIds(Ids []int) error {
_, err := Model.Delete("field_id in(?)", Ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除失败")
}
return nil
}
// 根据ID来修改信息
func EditSave(req *EditReq) error {
// 先根据ID来查询要修改的记录
entity, err := GetByID(req.FieldId)
if err != nil {
return err
}
// 修改实体
entity.ModelId = req.ModelId
entity.FieldName = req.FieldName
entity.FieldTitle = req.FieldTitle
entity.FieldType = req.FieldType
entity.FieldLength = req.FieldLength
entity.FieldDefault = req.FieldDefault
entity.FieldData = req.FieldData
entity.FieldDesc = req.FieldDesc
entity.FieldRules = gstr.Join(req.FieldRules, ",")
entity.UpdateBy = req.UpdateBy
entity.UpdateTime = gconv.Uint64(gtime.Timestamp())
entity.FieldWidth = req.FieldWidth
entity.FieldAlign = req.fieldAlign
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("修改失败")
}
return nil
}
// 获取所有数据
func SelectListAll(req *SelectPageReq) (list []*Entity, err error) {
model := Model
if req != nil {
if req.ModelId != 0 {
model = model.Where(Columns.ModelId, req.ModelId)
}
}
// 查询
list, err = model.Order("field_sort asc,field_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("查询失败")
return
}
return
}
//通过模型ID删除对应模型字段
func DeleteByModelIds(modelIds []int, tx *gdb.TX) error {
_, err := Model.TX(tx).Delete(Columns.ModelId+" in(?)", modelIds)
if err != nil {
g.Log().Error(err)
return gerror.New("删除字段信息失败")
}
return nil
}
@@ -0,0 +1,73 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package model_fields
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table model_fields.
type Entity struct {
FieldId uint64 `orm:"field_id,primary" json:"field_id"` // 模型字段ID
ModelId uint `orm:"model_id" json:"model_id"` // 模型ID
FieldName string `orm:"field_name" json:"field_name"` // 字段名称
FieldTitle string `orm:"field_title" json:"field_title"` // 字段标题
FieldType string `orm:"field_type" json:"field_type"` // 字段类型
FieldLength string `orm:"field_length" json:"field_length"` // 字段长度
FieldDefault string `orm:"field_default" json:"field_default"` // 字段默认值
FieldData string `orm:"field_data" json:"field_data"` // 字段数据
FieldDesc string `orm:"field_desc" json:"field_desc"` // 字段描述
FieldRules string `orm:"field_rules" json:"field_rules"` // 字段规则
FieldSort int64 `orm:"field_sort" json:"field_sort"` // 字段排序
FieldWidth string `orm:"field_width" json:"field_width"` // 字段列表显示宽度
FieldAlign string `orm:"field_align" json:"field_align"` // 字段列表对齐
CreateBy uint64 `orm:"create_by" json:"create_by"` // 创建人
UpdateBy uint64 `orm:"update_by" json:"update_by"` // 修改人
CreateTime uint64 `orm:"create_time" json:"create_time"` // 创建时间
UpdateTime uint64 `orm:"update_time" json:"update_time"` // 修改时间
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}
@@ -0,0 +1,375 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package model_fields
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table model_fields operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of model_fields.
Table = "model_fields"
// Model is the model object of model_fields.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table model_fields.
Columns = struct {
FieldId string // 模型字段ID
ModelId string // 模型ID
FieldName string // 字段名称
FieldTitle string // 字段标题
FieldType string // 字段类型
FieldLength string // 字段长度
FieldDefault string // 字段默认值
FieldData string // 字段数据
FieldDesc string // 字段描述
FieldRules string // 字段规则
FieldSort string // 字段排序
FieldWidth string //字段列表显示宽度
fieldAlign string //字段列表对齐
CreateBy string // 创建人
UpdateBy string // 修改人
CreateTime string // 创建时间
UpdateTime string // 修改时间
}{
FieldId: "field_id",
ModelId: "model_id",
FieldName: "field_name",
FieldTitle: "field_title",
FieldType: "field_type",
FieldLength: "field_length",
FieldDefault: "field_default",
FieldData: "field_data",
FieldDesc: "field_desc",
FieldRules: "field_rules",
FieldSort: "field_sort",
FieldWidth: "field_width",
fieldAlign: "field_align",
CreateBy: "create_by",
UpdateBy: "update_by",
CreateTime: "create_time",
UpdateTime: "update_time",
}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// As sets an alias name for current table.
func (m *arModel) As(as string) *arModel {
return &arModel{m.M.As(as)}
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy ...string) *arModel {
return &arModel{m.M.Order(orderBy...)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}
@@ -0,0 +1,24 @@
package model_fields
import "github.com/gogf/gf/frame/g"
//模型字段规则
type FieldRule struct {
FType string `json:"type"`
FTitle string `json:"title"`
FField string `json:"field"`
FValue interface{} `json:"value"`
FOptions g.List `json:"options"`
FAttr g.Map `json:"attr"` //设置组件普通的 HTML 特性
FProps g.Map `json:"props"`
FValidate []Validate `json:"validate"`
}
//字段验证规则
type Validate struct {
VType string `json:"type"`
VRequired bool `json:"required"`
VMessage string `json:"message"`
VMin int64 `json:"min"`
VTrigger string `json:"trigger"`
}
+264
View File
@@ -0,0 +1,264 @@
// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================
package model_info
import (
"fmt"
"gfast/app/model/admin/model_category"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
"github.com/gogf/gf/util/gconv"
)
// AddReq 用于存储新增请求的请求参数
type AddReq struct {
ModelCategoryId uint `p:"modelCategoryId" v:"required|min:1#模型分类id不能为空|模型分类id不能为空"`
ModelName string `p:"modelName" v:"required#模型标识不能为空"`
ModelTitle string `p:"modelTitle" v:"required#模型名称不能为空"`
ModelStatus uint `p:"modelStatus" v:"required#状态不能为空"`
ModelEngine string `p:"modelEngine" `
CreateBy int //添加人
}
// EditReq 用于存储修改请求参数
type EditReq struct {
ModelId int `p:"modelId" v:"required#主键ID不能为空"`
ModelCategoryId int `p:"modelCategoryId" `
ModelName string `p:"modelName" v:"required#模型标识不能为空"`
ModelTitle string `p:"modelTitle" `
ModelStatus int `p:"modelStatus" v:"required#状态不能为空"`
ModelEngine string `p:"modelEngine" `
UpdateBy int
}
//模型字段属性修改请求参数
type FieldsAttrReq struct {
ModelId int `p:"modelId" v:"required#主键ID不能为空"`
ModelPk string `p:"modelPk" `
ModelOrder string `p:"modelOrder" `
ModelSort string `p:"modelSort" `
ModelList string `p:"modelList" `
ModelEdit string `p:"modelEdit" `
ModelIndexes string `p:"modelIndexes" `
SearchList string `p:"searchList" `
}
type ListEntity struct {
Entity
CName string `orm:"c_name" json:"c_name" `
}
type StatusSetReq struct {
ModelId uint `p:"modelId" v:"required#模型ID不能为空"`
ModelStatus int `p:"modelStatus" v:"required#状态不能为空"`
}
// SelectPageReq 用于存储分页查询的请求参数
type SelectPageReq struct {
ModelName string `p:"modelName"` //模型标识
ModelTitle string `p:"modelTitle"` //模型名称
ModelStatus string `p"modelStatus"` //模型状态
ModelCategoryId string `p"modelCategoryId"` //模型分类
BeginTime string `p:"beginTime"` //开始时间
EndTime string `p:"endTime"` //结束时间
PageNum int `p:"pageNum"` //当前页码
PageSize int `p:"pageSize"` //每页数
}
type RemoveReq struct {
Ids []int `p:"ids"` //删除id
}
// GetPlugAdByID 根据ID查询记录
func GetByID(id int64) (*Entity, error) {
entity, err := Model.FindOne(id)
if err != nil {
g.Log().Error(err)
err = gerror.New("根据ID查询记录出错")
}
if entity == nil {
err = gerror.New("根据ID未能查询到记录")
}
return entity, nil
}
// AddSave 添加
func AddSave(req *AddReq) error {
if err := ModelExists(req.ModelName, 0); err != nil {
return err
}
entity := new(Entity)
entity.ModelCategoryId = req.ModelCategoryId
entity.ModelName = req.ModelName
entity.ModelTitle = req.ModelTitle
entity.ModelStatus = req.ModelStatus
entity.ModelEngine = req.ModelEngine
entity.CreateBy = gconv.Uint64(req.CreateBy)
time := gconv.Uint64(gtime.Timestamp())
entity.CreateTime = time
entity.UpdateTime = time
result, err := entity.Insert()
if err != nil {
return err
}
_, err = result.LastInsertId()
if err != nil {
return err
}
return nil
}
//判断模型是否存在
func ModelExists(name string, id int) error {
var res *Entity
if id != 0 {
res, _ = Model.Where(Columns.ModelName, name).And(Columns.ModelId+" != ", id).One()
} else {
res, _ = Model.Where(Columns.ModelName, name).One()
}
if res != nil {
return gerror.New("模型标识已经存在")
}
return nil
}
// 删除模型
func DeleteByIds(Ids []int, tx *gdb.TX) error {
_, err := Model.TX(tx).Delete("model_id in(?)", Ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除失败")
}
return nil
}
// 根据ID来修改信息
func EditSave(req *EditReq) error {
if err := ModelExists(req.ModelName, req.ModelId); err != nil {
return err
}
// 先根据ID来查询要修改的记录
entity, err := GetByID(gconv.Int64(req.ModelId))
if err != nil {
return err
}
// 修改实体
entity.ModelCategoryId = gconv.Uint(req.ModelCategoryId)
entity.ModelName = req.ModelName
entity.ModelTitle = req.ModelTitle
entity.ModelStatus = gconv.Uint(req.ModelStatus)
entity.ModelEngine = req.ModelEngine
entity.UpdateBy = gconv.Uint64(req.UpdateBy)
entity.UpdateTime = gconv.Uint64(gtime.Timestamp())
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("修改失败")
}
return nil
}
// 分页查询,返回值total总记录数,page当前页
func SelectListByPage(req *SelectPageReq) (total int, page int, list []*ListEntity, err error) {
model := g.DB().Table(Table + " info")
if req != nil {
if req.ModelName != "" {
model.Where("info.model_name like ?", "%"+req.ModelName+"%")
}
if req.ModelTitle != "" {
model.Where("info.model_title like ?", "%"+req.ModelTitle+"%")
}
if req.ModelStatus != "" {
model.Where("info.model_status", gconv.Uint(req.ModelStatus))
}
if req.ModelCategoryId != "" {
model.Where("info.model_category_id", gconv.Uint(req.ModelCategoryId))
}
}
model = model.LeftJoin(model_category.Table+" cate", "cate.c_id=info.model_category_id")
// 查询总记录数(总行数)
total, err = model.Count()
if err != nil {
g.Log().Error(err)
err = gerror.New("获取总记录数失败")
return
}
if req.PageNum == 0 {
req.PageNum = 1
}
page = req.PageNum
if req.PageSize == 0 {
req.PageSize = 10
}
// 分页排序查询
var res gdb.Result
res, err = model.Fields("info.*,cate.c_name").Page(page, req.PageSize).Order("info.model_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("查询失败")
return
}
err = res.Structs(&list)
if err != nil {
g.Log().Error(err)
err = gerror.New("查询失败")
return
}
return
}
// 获取所有数据
func SelectListAll(req *SelectPageReq) (list []*Entity, err error) {
model := Model
if req != nil {
if req.ModelName != "" {
model.Where("model_name like ?", "%"+req.ModelName+"%")
}
if req.ModelTitle != "" {
model.Where("model_title = ?", req.ModelTitle)
}
}
// 查询
list, err = model.Order("model_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("查询失败")
return
}
return
}
//设置模型状态
func SetStatus(req *StatusSetReq) error {
if req != nil {
entity, err := Model.Where(Columns.ModelId, req.ModelId).One()
if err != nil {
g.Log().Error(err)
return gerror.New("获取模型信息失败")
}
entity.ModelStatus = gconv.Uint(req.ModelStatus)
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("设置状态失败")
}
}
return nil
}
//通过模型分类ID获取模型
func GetModelsByCateIds(cateIds []int) (models []*Entity, err error) {
models, err = Model.Fields(fmt.Sprintf("%s,%s,%s", Columns.ModelId, Columns.ModelName, Columns.ModelTitle)).
Where(Columns.ModelCategoryId+" in(?)", cateIds).
Order(Columns.ModelId + " ASC ").FindAll()
if err != nil {
g.Log().Error(err)
err = gerror.New("获取模型信息失败")
}
return
}
@@ -0,0 +1,73 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package model_info
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table model_info.
type Entity struct {
ModelId uint `orm:"model_id,primary" json:"model_id"` // 模型ID
ModelCategoryId uint `orm:"model_category_id" json:"model_category_id"` // 模板分类id
ModelName string `orm:"model_name" json:"model_name"` // 模型标识
ModelTitle string `orm:"model_title" json:"model_title"` // 模型名称
ModelPk string `orm:"model_pk" json:"model_pk"` // 主键字段
ModelOrder string `orm:"model_order" json:"model_order"` // 默认排序字段
ModelSort string `orm:"model_sort" json:"model_sort"` // 表单字段排序
ModelList string `orm:"model_list" json:"model_list"` // 列表显示字段,为空显示全部
ModelEdit string `orm:"model_edit" json:"model_edit"` // 可编辑字段,为空则除主键外均可以编辑
ModelIndexes string `orm:"model_indexes" json:"model_indexes"` // 索引字段
SearchList string `orm:"search_list" json:"search_list"` // 高级搜索的字段
CreateTime uint64 `orm:"create_time" json:"create_time"` // 创建时间
UpdateTime uint64 `orm:"update_time" json:"update_time"` // 更新时间
ModelStatus uint `orm:"model_status" json:"model_status"` // 状态
ModelEngine string `orm:"model_engine" json:"model_engine"` // 数据库引擎
CreateBy uint64 `orm:"create_by" json:"create_by"` // 创建人
UpdateBy uint64 `orm:"update_by" json:"update_by"` // 修改人
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}
@@ -0,0 +1,375 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package model_info
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table model_info operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of model_info.
Table = "model_info"
// Model is the model object of model_info.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table model_info.
Columns = struct {
ModelId string // 模型ID
ModelCategoryId string // 模板分类id
ModelName string // 模型标识
ModelTitle string // 模型名称
ModelPk string // 主键字段
ModelOrder string // 默认排序字段
ModelSort string // 表单字段排序
ModelList string // 列表显示字段,为空显示全部
ModelEdit string // 可编辑字段,为空则除主键外均可以编辑
ModelIndexes string // 索引字段
SearchList string // 高级搜索的字段
CreateTime string // 创建时间
UpdateTime string // 更新时间
ModelStatus string // 状态
ModelEngine string // 数据库引擎
CreateBy string // 创建人
UpdateBy string // 修改人
}{
ModelId: "model_id",
ModelCategoryId: "model_category_id",
ModelName: "model_name",
ModelTitle: "model_title",
ModelPk: "model_pk",
ModelOrder: "model_order",
ModelSort: "model_sort",
ModelList: "model_list",
ModelEdit: "model_edit",
ModelIndexes: "model_indexes",
SearchList: "search_list",
CreateTime: "create_time",
UpdateTime: "update_time",
ModelStatus: "model_status",
ModelEngine: "model_engine",
CreateBy: "create_by",
UpdateBy: "update_by",
}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// As sets an alias name for current table.
func (m *arModel) As(as string) *arModel {
return &arModel{m.M.As(as)}
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy ...string) *arModel {
return &arModel{m.M.Order(orderBy...)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}
+41 -25
View File
@@ -1,6 +1,8 @@
package plug_ad
import (
"gfast/app/model/admin/plug_adtype"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
@@ -8,39 +10,45 @@ import (
// AddReq 用于存储新增广告请求的请求参数
type AddReq struct {
AdName string `p:"adName"` // 广告名称
AdAdtypeid int `p:"adAdtypeid"` // 所属位置
AdCheckid int `p:"adCheckid"` // 1=图片 2=JS
AdJs string `p:"adJs"` // JS代码
AdPic string `p:"adPic"` // 广告图片URL
AdUrl string `p:"adUrl"` // 广告链接
AdContent string `p:"adContent"` // 广告文字内容
AdSort int `p:"adSort"` // 排序
AdOpen int `p:"adOpen"` // 1=审核 0=未审核
AdName string `p:"adName" v:"required#名称不能为空"` // 广告名称
AdAdtypeid int `p:"adAdtypeid"` // 所属位置
AdCheckid int `p:"adCheckid"` // 1=图片 2=JS
AdJs string `p:"adJs"` // JS代码
AdPic string `p:"adPic"` // 广告图片URL
AdUrl string `p:"adUrl"` // 广告链接
AdContent string `p:"adContent"` // 广告文字内容
AdSort int `p:"adSort"` // 排序
AdOpen int `p:"adOpen"` // 1=审核 0=未审核
}
// EditReq 用于存储修改广告请求参数
// EditReq 用于存储修改广告请求参数
type EditReq struct {
PlugAdID int64 `p:"plugAdID"`
PlugAdID int64 `p:"plugAdID" v:"required|min:1#广告id不能为空|广告id参数错误"`
AddReq
}
// SelectPageReq 用于存储分页查询广告的请求参数
type SelectPageReq struct {
AdName string `p:"adName"` // 广告名称
PageNo int64 `p:"pageNo"` // 当前页
PageNo int64 `p:"pageNum"` // 当前页
PageSize int64 `p:"pageSize"` // 每页显示记录数
}
// 用于存储分页查询的数据
type ListEntity struct {
Entity
AdTypeName string `orm:"adtype_name" json:"adtype_name" ` // 广告所属位置
}
// GetPlugAdByID 根据ID查询广告记录
func GetPlugAdByID(id int64) (*Entity, error) {
entity, err := Model.FindOne("ad_id", id)
if err != nil {
g.Log().Error(err)
err = gerror.New("根据ID查询广告记录出错")
return nil, gerror.New("根据ID查询广告记录出错")
}
if entity == nil {
err = gerror.New("根据ID未能查询到广告记录")
return nil, gerror.New("根据ID未能查询到广告记录")
}
return entity, nil
}
@@ -62,15 +70,14 @@ func AddSave(req *AddReq) error {
_, err := entity.Insert()
if err != nil {
g.Log().Error(err)
err = gerror.New("保存失败")
return err
return gerror.New("添加广告记录入库失败")
}
return nil
}
// 删除广告
func DeleteByIDs(Ids []int) error {
_, err := Model.Delete("ad_id in(?)", Ids)
// 批量删除广告记录
func DeleteByIDs(ids []int) error {
_, err := Model.Delete("ad_id in(?)", ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除广告失败")
@@ -78,7 +85,7 @@ func DeleteByIDs(Ids []int) error {
return nil
}
// 根据广告ID来修改广告信息
// 根据广告ID来修改广告信息
func EditSave(editReq *EditReq) error {
// 先根据ID来查询要修改的广告记录
entity, err := GetPlugAdByID(editReq.PlugAdID)
@@ -98,19 +105,20 @@ func EditSave(editReq *EditReq) error {
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("修改广告失败")
return gerror.New("修改广告失败")
}
return nil
}
// 分页查询,返回值total总记录数,page当前页
func SelectListByPage(req *SelectPageReq) (total int, page int64, list []*Entity, err error) {
model := Model
func SelectListByPage(req *SelectPageReq) (total int, page int64, list []*ListEntity, err error) {
model := g.DB().Table(Table + " ad")
if req != nil {
if req.AdName != "" {
model = model.Where("ad_name like ?", "%"+req.AdName+"%")
model.Where("ad.ad_name like ?", "%"+req.AdName+"%")
}
}
model = model.LeftJoin(plug_adtype.Table+" type", "type.adtype_id=ad.ad_adtypeid")
// 查询广告位总记录数(总行数)
total, err = model.Count()
if err != nil {
@@ -126,7 +134,15 @@ func SelectListByPage(req *SelectPageReq) (total int, page int64, list []*Entity
req.PageSize = 10
}
// 分页排序查询
list, err = model.Page(int(page), int(req.PageSize)).Order("ad_sort asc,ad_id asc").All()
var res gdb.Result
res, err = model.Fields("ad.*,type.adtype_name").Page(int(page), int(req.PageSize)).Order("ad.ad_sort asc,ad.ad_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("分页查询广告失败")
return 0, 0, nil, err
}
err = res.Structs(&list)
if err != nil {
g.Log().Error(err)
err = gerror.New("分页查询广告失败")
+11 -10
View File
@@ -17,14 +17,14 @@ type AddReq struct {
// EditReq 用于存储修改广告位请求参数
type EditReq struct {
AdtypeID int64 `p:"adtypeID" v:"required|min:1#主键ID不能为空|主键ID值错误"`
AdtypeID int64 `p:"adTypeID" v:"required|min:1#主键ID不能为空|主键ID值错误"`
AddReq
}
// SelectPageReq 用于存储分页查询广告位的请求参数
type SelectPageReq struct {
AdtypeName string `p:"adTypeName"` // 广告位名称
PageNo int64 `p:"pageNo"` // 当前页
PageNo int64 `p:"pageNum"` // 当前页
PageSize int64 `p:"pageSize"` // 每页显示记录数
}
@@ -33,24 +33,24 @@ func GetAdtypeByID(id int64) (*Entity, error) {
entity, err := Model.FindOne(id)
if err != nil {
g.Log().Error(err)
err = gerror.New("根据ID查询广告位记录出错")
return nil, gerror.New("根据ID查询广告位记录出错")
}
if entity == nil {
err = gerror.New("根据ID未能查询到广告位记录")
return nil, gerror.New("根据ID未能查询到广告位记录")
}
return entity, nil
}
// 根据广告位的名称来判断是否已存在相同名称的广告位
func CheakAdtypeNameUnique(adtypeName string, adTypeId int64) error {
// 根据广告位的名称和ID来判断是否已存在相同名称的广告位
func CheakAdtypeNameUnique(adTypeName string, adTypeId int64) error {
var (
entity *Entity
err error
)
if adTypeId == 0 {
entity, err = Model.FindOne(Columns.AdtypeName, adtypeName)
entity, err = Model.FindOne(Columns.AdtypeName, adTypeName)
} else {
entity, err = Model.Where(Columns.AdtypeName, adtypeName).And(Columns.AdtypeId+"!=?", adTypeId).FindOne()
entity, err = Model.Where(Columns.AdtypeName, adTypeName).And(Columns.AdtypeId+"!=?", adTypeId).FindOne()
}
if err != nil {
g.Log().Error(err)
@@ -70,7 +70,7 @@ func AddSave(req *AddReq) error {
_, err := entity.Insert()
if err != nil {
g.Log().Error(err)
err = gerror.New("保存广告位失败")
return gerror.New("保存广告位失败")
}
return nil
}
@@ -90,7 +90,8 @@ func EditSave(editReq *EditReq) error {
// 先根据ID来查询要修改的广告位记录
entity, err := GetAdtypeByID(editReq.AdtypeID)
if err != nil {
return err
g.Log().Error(err)
return gerror.New("查询要修改的记录时出错")
}
// 修改实体
entity.AdtypeName = editReq.AdtypeName
+149
View File
@@ -0,0 +1,149 @@
// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================
package plug_link
import (
"gfast/app/model/admin/plug_linktype"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/os/gtime"
)
// AddReq 用于存储新增链接请求的请求参数
type AddReq struct {
LinkName string `p:"linkName" v:"required#名称不能为空"` // 链接名称
LinkUrl string `p:"linkUrl"` // 链接URL
LinkTarget string `p:"linkTarget"` // 打开方式
LinkTypeID int `p:"linkTypeID"` // 所属栏目ID
LinkQQ string `p:"linkQQ"` // 联系QQ
LinkOrder int64 `p:"linkOrder"` // 排序
LinkOpen int `p:"linkOpen"` // 0禁用1启用(是否审核)
}
// EditReq 用于存储修改广告位请求参数
type EditReq struct {
PlugLinkID int64 `p:"plugLinkID" v:"required|min:1#广告id不能为空|广告id参数错误"`
AddReq
}
// SelectPageReq 用于存储分页查询广告的请求参数
type SelectPageReq struct {
LinkName string `p:"linkName"` // 广告名称
PageNo int64 `p:"pageNum"` // 当前页
PageSize int64 `p:"pageSize"` // 每页显示记录数
}
// 用于存储分页查询的数据
type ListEntity struct {
Entity
LinkTypeName string `orm:"linktype_name" json:"linktype_name" ` // 友情链接所属分类
}
// GetPlugLinkByID 根据ID查询链接记录
func GetPlugLinkByID(id int64) (*Entity, error) {
entity, err := Model.FindOne("link_id", id)
if err != nil {
g.Log().Error(err)
return nil, gerror.New("根据ID查询链接记录出错")
}
if entity == nil {
return nil, gerror.New("根据ID未能查询到链接记录")
}
return entity, nil
}
// AddSave 添加友情链接
func AddSave(req *AddReq) error {
var entity Entity
entity.LinkName = req.LinkName
entity.LinkUrl = req.LinkUrl
entity.LinkTarget = req.LinkTarget
entity.LinkTypeid = req.LinkTypeID
entity.LinkQq = req.LinkQQ
entity.LinkAddtime = int(gtime.Timestamp()) // 添加时间
entity.LinkOrder = req.LinkOrder
entity.LinkOpen = req.LinkOpen
// 保存实体
_, err := entity.Insert()
if err != nil {
g.Log().Error(err)
return gerror.New("保存失败")
}
return nil
}
// 根据ID批量删除链接
func DeleteByIDs(ids []int) error {
_, err := Model.Delete("link_id in(?)", ids)
if err != nil {
g.Log().Error(err)
return gerror.New("删除链接失败")
}
return nil
}
// 根据ID来修改链接信息
func EditSave(editReq *EditReq) error {
// 先根据ID来查询要修改的链接记录
entity, err := GetPlugLinkByID(editReq.PlugLinkID)
if err != nil {
return err
}
// 修改实体
entity.LinkName = editReq.LinkName
entity.LinkUrl = editReq.LinkUrl
entity.LinkTarget = editReq.LinkTarget
entity.LinkTypeid = editReq.LinkTypeID
entity.LinkQq = editReq.LinkQQ
entity.LinkOrder = editReq.LinkOrder
entity.LinkOpen = editReq.LinkOpen
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("修改栏目失败")
}
return nil
}
// 分页查询,返回值total总记录数,page当前页
func SelectListByPage(req *SelectPageReq) (total int, page int64, list []*ListEntity, err error) {
model := g.DB().Table(Table + " link")
if req != nil {
if req.LinkName != "" {
model.Where("link.link_name like ?", "%"+req.LinkName+"%")
}
}
model = model.LeftJoin(plug_linktype.Table+" type", "type.linktype_id=link.link_typeid")
// 查询友情链接总记录数(总行数)
total, err = model.Count()
if err != nil {
g.Log().Error(err)
err = gerror.New("获取总记录数失败")
return 0, 0, nil, err
}
if req.PageNo == 0 {
req.PageNo = 1
}
page = req.PageNo
if req.PageSize == 0 {
req.PageSize = 10
}
// 分页排序查询
var res gdb.Result
res, err = model.Fields("link.*,type.linktype_name").Page(int(page), int(req.PageSize)).Order("link.link_order asc,link.link_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("分页查询友情链接失败")
return 0, 0, nil, err
}
err = res.Structs(&list)
if err != nil {
g.Log().Error(err)
err = gerror.New("分页查询广告失败")
return 0, 0, nil, err
}
return total, page, list, nil
}
@@ -0,0 +1,65 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package plug_link
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table plug_link.
type Entity struct {
LinkId int `orm:"link_id,primary" json:"link_id"` //
LinkName string `orm:"link_name" json:"link_name"` // 链接名称
LinkUrl string `orm:"link_url" json:"link_url"` // 链接URL
LinkTarget string `orm:"link_target" json:"link_target"` // 打开方式
LinkTypeid int `orm:"link_typeid" json:"link_typeid"` // 所属栏目ID
LinkQq string `orm:"link_qq" json:"link_qq"` // 联系QQ
LinkOrder int64 `orm:"link_order" json:"link_order"` // 排序
LinkAddtime int `orm:"link_addtime" json:"link_addtime"` // 添加时间
LinkOpen int `orm:"link_open" json:"link_open"` // 0禁用1启用
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}
@@ -0,0 +1,359 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package plug_link
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table plug_link operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of plug_link.
Table = "plug_link"
// Model is the model object of plug_link.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table plug_link.
Columns = struct {
LinkId string //
LinkName string // 链接名称
LinkUrl string // 链接URL
LinkTarget string // 打开方式
LinkTypeid string // 所属栏目ID
LinkQq string // 联系QQ
LinkOrder string // 排序
LinkAddtime string // 添加时间
LinkOpen string // 0禁用1启用
}{
LinkId: "link_id",
LinkName: "link_name",
LinkUrl: "link_url",
LinkTarget: "link_target",
LinkTypeid: "link_typeid",
LinkQq: "link_qq",
LinkOrder: "link_order",
LinkAddtime: "link_addtime",
LinkOpen: "link_open",
}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// As sets an alias name for current table.
func (m *arModel) As(as string) *arModel {
return &arModel{m.M.As(as)}
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy ...string) *arModel {
return &arModel{m.M.Order(orderBy...)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}
@@ -0,0 +1,142 @@
// ============================================================================
// This is auto-generated by gf cli tool only once. Fill this file as you wish.
// ============================================================================
package plug_linktype
import (
"github.com/gogf/gf/errors/gerror"
"github.com/gogf/gf/frame/g"
)
// AddReq 用于获取添加栏目的请求参数
type AddReq struct {
LinktypeName string `p:"linkTypeName" v:"required#栏目名称不能为空"` // 栏目名称
LinktypeOrder int `p:"linkTypeOrder" v:"required#栏目排序不能为空"` // 栏目排序
}
// EditReq 用于存储修改栏目的请求参数
type EditReq struct {
LinktypeId int64 `p:"linkTypeID" v:"required|min:1#主键ID不能为空|主键ID值错误"`
AddReq
}
// SelectPageReq 用于存储分页查询栏目的请求参数
type SelectPageReq struct {
LinktypeName string `p:"linkTypeName"` // 栏目名称,用于根据栏目名来模糊查询
PageNo int64 `p:"pageNum"` // 当前页
PageSize int64 `p:"pageSize"` // 每页显示记录数
}
// GetLinkTypeByID 根据ID查询栏目记录
func GetLinkTypeByID(id int64) (*Entity, error) {
entity, err := Model.FindOne(id)
if err != nil {
g.Log().Error(err)
return nil, gerror.New("根据ID查询栏目记录出错")
}
if entity == nil {
return nil, gerror.New("根据ID未能查询到栏目记录")
}
return entity, nil
}
// CheakLinkTypeNameUnique 用于检测栏目名称唯一性
func CheakLinkTypeNameUnique(linkTypeName string, linkTypeID int64) error {
var (
entity *Entity // 用于存储查询出的记录
err error
)
// 此函数用于增加栏目时没有ID传入
if linkTypeID == 0 {
entity, err = Model.FindOne(Columns.LinktypeName, linkTypeName)
} else {
// 用于修改时有ID传入
entity, err = Model.Where(Columns.LinktypeName, linkTypeName).And(Columns.LinktypeId+"!=?", linkTypeID).FindOne()
}
if err != nil {
g.Log().Error(err)
return gerror.New("校验栏目名称唯一性出错")
}
if entity != nil {
return gerror.New("栏目名称已存在")
}
return nil
}
// AddSave 用于添加栏目
func AddSave(req *AddReq) error {
// 定义一个实体用于接收req中的信息并将信息添加到数据库
var entity Entity
entity.LinktypeName = req.LinktypeName
entity.LinktypeOrder = uint(req.LinktypeOrder)
// 调用实体中的Insert方法将信息添加到数据库中
_, err := entity.Insert()
if err != nil {
// 错误放入错误日志
g.Log().Error(err)
// New创建并返回从给定文本格式化的错误
return gerror.New("信息插入数据库失败")
}
return nil
}
// DeleteLinkTypeByID 根据ID批量删除栏目
func DeleteLinkTypeByID(id []int) error {
_, err := Model.Where("linktype_id in(?)", id).Delete()
if err != nil {
g.Log().Error(err)
return gerror.New("批量删除栏目出错")
}
return nil
}
// EditSave 修改
func EditSave(req *EditReq) error {
// 先根据ID来查询要修改的广告位记录
entity, err := GetLinkTypeByID(req.LinktypeId)
if err != nil {
return err
}
// 修改实体
entity.LinktypeName = req.LinktypeName
entity.LinktypeOrder = uint(req.LinktypeOrder)
_, err = entity.Update()
if err != nil {
g.Log().Error(err)
return gerror.New("修改栏目失败")
}
return nil
}
// 分页查询,返回值total总记录数,page当前页
func SelectListByPage(req *SelectPageReq) (total int, page int64, list []*Entity, err error) {
model := Model
if req != nil {
if req.LinktypeName != "" {
model = model.Where("linktype_name like ?", "%"+req.LinktypeName+"%")
}
}
// 查询栏目总记录数(总行数)
total, err = model.Count()
if err != nil {
g.Log().Error(err)
err = gerror.New("获取总记录数失败")
return 0, 0, nil, err
}
if req.PageNo == 0 {
req.PageNo = 1
}
page = req.PageNo
if req.PageSize == 0 {
req.PageSize = 10
}
// 分页排序查询
list, err = model.Page(int(page), int(req.PageSize)).Order("linktype_order asc,linktype_id asc").All()
if err != nil {
g.Log().Error(err)
err = gerror.New("分页查询栏目失败")
return 0, 0, nil, err
}
return total, page, list, nil
}
@@ -0,0 +1,59 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package plug_linktype
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
)
// Entity is the golang structure for table plug_linktype.
type Entity struct {
LinktypeId int `orm:"linktype_id,primary" json:"linktype_id"` //
LinktypeName string `orm:"linktype_name" json:"linktype_name"` // 所属栏目名称
LinktypeOrder uint `orm:"linktype_order" json:"linktype_order"` // 排序
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (r *Entity) OmitEmpty() *arModel {
return Model.Data(r).OmitEmpty()
}
// Inserts does "INSERT...INTO..." statement for inserting current object into table.
func (r *Entity) Insert() (result sql.Result, err error) {
return Model.Data(r).Insert()
}
// InsertIgnore does "INSERT IGNORE INTO ..." statement for inserting current object into table.
func (r *Entity) InsertIgnore() (result sql.Result, err error) {
return Model.Data(r).InsertIgnore()
}
// Replace does "REPLACE...INTO..." statement for inserting current object into table.
// If there's already another same record in the table (it checks using primary key or unique index),
// it deletes it and insert this one.
func (r *Entity) Replace() (result sql.Result, err error) {
return Model.Data(r).Replace()
}
// Save does "INSERT...INTO..." statement for inserting/updating current object into table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Save() (result sql.Result, err error) {
return Model.Data(r).Save()
}
// Update does "UPDATE...WHERE..." statement for updating current object from table.
// It updates the record if there's already another same record in the table
// (it checks using primary key or unique index).
func (r *Entity) Update() (result sql.Result, err error) {
return Model.Data(r).Where(gdb.GetWhereConditionOfStruct(r)).Update()
}
// Delete does "DELETE FROM...WHERE..." statement for deleting current object from table.
func (r *Entity) Delete() (result sql.Result, err error) {
return Model.Where(gdb.GetWhereConditionOfStruct(r)).Delete()
}
@@ -0,0 +1,347 @@
// ==========================================================================
// This is auto-generated by gf cli tool. You may not really want to edit it.
// ==========================================================================
package plug_linktype
import (
"database/sql"
"github.com/gogf/gf/database/gdb"
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/frame/gmvc"
"time"
)
// arModel is a active record design model for table plug_linktype operations.
type arModel struct {
gmvc.M
}
var (
// Table is the table name of plug_linktype.
Table = "plug_linktype"
// Model is the model object of plug_linktype.
Model = &arModel{g.DB("default").Table(Table).Safe()}
// Columns defines and stores column names for table plug_linktype.
Columns = struct {
LinktypeId string //
LinktypeName string // 所属栏目名称
LinktypeOrder string // 排序
}{
LinktypeId: "linktype_id",
LinktypeName: "linktype_name",
LinktypeOrder: "linktype_order",
}
)
// FindOne is a convenience method for Model.FindOne.
// See Model.FindOne.
func FindOne(where ...interface{}) (*Entity, error) {
return Model.FindOne(where...)
}
// FindAll is a convenience method for Model.FindAll.
// See Model.FindAll.
func FindAll(where ...interface{}) ([]*Entity, error) {
return Model.FindAll(where...)
}
// FindValue is a convenience method for Model.FindValue.
// See Model.FindValue.
func FindValue(fieldsAndWhere ...interface{}) (gdb.Value, error) {
return Model.FindValue(fieldsAndWhere...)
}
// FindArray is a convenience method for Model.FindArray.
// See Model.FindArray.
func FindArray(fieldsAndWhere ...interface{}) ([]gdb.Value, error) {
return Model.FindArray(fieldsAndWhere...)
}
// FindCount is a convenience method for Model.FindCount.
// See Model.FindCount.
func FindCount(where ...interface{}) (int, error) {
return Model.FindCount(where...)
}
// Insert is a convenience method for Model.Insert.
func Insert(data ...interface{}) (result sql.Result, err error) {
return Model.Insert(data...)
}
// InsertIgnore is a convenience method for Model.InsertIgnore.
func InsertIgnore(data ...interface{}) (result sql.Result, err error) {
return Model.InsertIgnore(data...)
}
// Replace is a convenience method for Model.Replace.
func Replace(data ...interface{}) (result sql.Result, err error) {
return Model.Replace(data...)
}
// Save is a convenience method for Model.Save.
func Save(data ...interface{}) (result sql.Result, err error) {
return Model.Save(data...)
}
// Update is a convenience method for Model.Update.
func Update(dataAndWhere ...interface{}) (result sql.Result, err error) {
return Model.Update(dataAndWhere...)
}
// Delete is a convenience method for Model.Delete.
func Delete(where ...interface{}) (result sql.Result, err error) {
return Model.Delete(where...)
}
// As sets an alias name for current table.
func (m *arModel) As(as string) *arModel {
return &arModel{m.M.As(as)}
}
// TX sets the transaction for current operation.
func (m *arModel) TX(tx *gdb.TX) *arModel {
return &arModel{m.M.TX(tx)}
}
// Master marks the following operation on master node.
func (m *arModel) Master() *arModel {
return &arModel{m.M.Master()}
}
// Slave marks the following operation on slave node.
// Note that it makes sense only if there's any slave node configured.
func (m *arModel) Slave() *arModel {
return &arModel{m.M.Slave()}
}
// LeftJoin does "LEFT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").LeftJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").LeftJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) LeftJoin(table ...string) *arModel {
return &arModel{m.M.LeftJoin(table...)}
}
// RightJoin does "RIGHT JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").RightJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").RightJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) RightJoin(table ...string) *arModel {
return &arModel{m.M.RightJoin(table...)}
}
// InnerJoin does "INNER JOIN ... ON ..." statement on the model.
// The parameter <table> can be joined table and its joined condition,
// and also with its alias name, like:
// Table("user").InnerJoin("user_detail", "user_detail.uid=user.uid")
// Table("user", "u").InnerJoin("user_detail", "ud", "ud.uid=u.uid")
func (m *arModel) InnerJoin(table ...string) *arModel {
return &arModel{m.M.InnerJoin(table...)}
}
// Fields sets the operation fields of the model, multiple fields joined using char ','.
func (m *arModel) Fields(fields string) *arModel {
return &arModel{m.M.Fields(fields)}
}
// FieldsEx sets the excluded operation fields of the model, multiple fields joined using char ','.
func (m *arModel) FieldsEx(fields string) *arModel {
return &arModel{m.M.FieldsEx(fields)}
}
// Option sets the extra operation option for the model.
func (m *arModel) Option(option int) *arModel {
return &arModel{m.M.Option(option)}
}
// OmitEmpty sets OPTION_OMITEMPTY option for the model, which automatically filers
// the data and where attributes for empty values.
func (m *arModel) OmitEmpty() *arModel {
return &arModel{m.M.OmitEmpty()}
}
// Filter marks filtering the fields which does not exist in the fields of the operated table.
func (m *arModel) Filter() *arModel {
return &arModel{m.M.Filter()}
}
// Where sets the condition statement for the model. The parameter <where> can be type of
// string/map/gmap/slice/struct/*struct, etc. Note that, if it's called more than one times,
// multiple conditions will be joined into where statement using "AND".
// Eg:
// Where("uid=10000")
// Where("uid", 10000)
// Where("money>? AND name like ?", 99999, "vip_%")
// Where("uid", 1).Where("name", "john")
// Where("status IN (?)", g.Slice{1,2,3})
// Where("age IN(?,?)", 18, 50)
// Where(User{ Id : 1, UserName : "john"})
func (m *arModel) Where(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Where(where, args...)}
}
// And adds "AND" condition to the where statement.
func (m *arModel) And(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.And(where, args...)}
}
// Or adds "OR" condition to the where statement.
func (m *arModel) Or(where interface{}, args ...interface{}) *arModel {
return &arModel{m.M.Or(where, args...)}
}
// Group sets the "GROUP BY" statement for the model.
func (m *arModel) Group(groupBy string) *arModel {
return &arModel{m.M.Group(groupBy)}
}
// Order sets the "ORDER BY" statement for the model.
func (m *arModel) Order(orderBy ...string) *arModel {
return &arModel{m.M.Order(orderBy...)}
}
// Limit sets the "LIMIT" statement for the model.
// The parameter <limit> can be either one or two number, if passed two number is passed,
// it then sets "LIMIT limit[0],limit[1]" statement for the model, or else it sets "LIMIT limit[0]"
// statement.
func (m *arModel) Limit(limit ...int) *arModel {
return &arModel{m.M.Limit(limit...)}
}
// Offset sets the "OFFSET" statement for the model.
// It only makes sense for some databases like SQLServer, PostgreSQL, etc.
func (m *arModel) Offset(offset int) *arModel {
return &arModel{m.M.Offset(offset)}
}
// Page sets the paging number for the model.
// The parameter <page> is started from 1 for paging.
// Note that, it differs that the Limit function start from 0 for "LIMIT" statement.
func (m *arModel) Page(page, limit int) *arModel {
return &arModel{m.M.Page(page, limit)}
}
// Batch sets the batch operation number for the model.
func (m *arModel) Batch(batch int) *arModel {
return &arModel{m.M.Batch(batch)}
}
// Cache sets the cache feature for the model. It caches the result of the sql, which means
// if there's another same sql request, it just reads and returns the result from cache, it
// but not committed and executed into the database.
//
// If the parameter <duration> < 0, which means it clear the cache with given <name>.
// If the parameter <duration> = 0, which means it never expires.
// If the parameter <duration> > 0, which means it expires after <duration>.
//
// The optional parameter <name> is used to bind a name to the cache, which means you can later
// control the cache like changing the <duration> or clearing the cache with specified <name>.
//
// Note that, the cache feature is disabled if the model is operating on a transaction.
func (m *arModel) Cache(duration time.Duration, name ...string) *arModel {
return &arModel{m.M.Cache(duration, name...)}
}
// Data sets the operation data for the model.
// The parameter <data> can be type of string/map/gmap/slice/struct/*struct, etc.
// Eg:
// Data("uid=10000")
// Data("uid", 10000)
// Data(g.Map{"uid": 10000, "name":"john"})
// Data(g.Slice{g.Map{"uid": 10000, "name":"john"}, g.Map{"uid": 20000, "name":"smith"})
func (m *arModel) Data(data ...interface{}) *arModel {
return &arModel{m.M.Data(data...)}
}
// All does "SELECT FROM ..." statement for the model.
// It retrieves the records from table and returns the result as []*Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) All(where ...interface{}) ([]*Entity, error) {
all, err := m.M.All(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// One retrieves one record from table and returns the result as *Entity.
// It returns nil if there's no record retrieved with the given conditions from table.
//
// The optional parameter <where> is the same as the parameter of Model.Where function,
// see Model.Where.
func (m *arModel) One(where ...interface{}) (*Entity, error) {
one, err := m.M.One(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindOne retrieves and returns a single Record by Model.WherePri and Model.One.
// Also see Model.WherePri and Model.One.
func (m *arModel) FindOne(where ...interface{}) (*Entity, error) {
one, err := m.M.FindOne(where...)
if err != nil {
return nil, err
}
var entity *Entity
if err = one.Struct(&entity); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entity, nil
}
// FindAll retrieves and returns Result by by Model.WherePri and Model.All.
// Also see Model.WherePri and Model.All.
func (m *arModel) FindAll(where ...interface{}) ([]*Entity, error) {
all, err := m.M.FindAll(where...)
if err != nil {
return nil, err
}
var entities []*Entity
if err = all.Structs(&entities); err != nil && err != sql.ErrNoRows {
return nil, err
}
return entities, nil
}
// Chunk iterates the table with given size and callback function.
func (m *arModel) Chunk(limit int, callback func(entities []*Entity, err error) bool) {
m.M.Chunk(limit, func(result gdb.Result, err error) bool {
var entities []*Entity
err = result.Structs(&entities)
if err == sql.ErrNoRows {
return false
}
return callback(entities, err)
})
}
// LockUpdate sets the lock for update for current operation.
func (m *arModel) LockUpdate() *arModel {
return &arModel{m.M.LockUpdate()}
}
// LockShared sets the lock in share mode for current operation.
func (m *arModel) LockShared() *arModel {
return &arModel{m.M.LockShared()}
}
// Unscoped enables/disables the soft deleting feature.
func (m *arModel) Unscoped() *arModel {
return &arModel{m.M.Unscoped()}
}