position.go 2.8 KB
package models

import (
	"fmt"
	"time"

	"github.com/astaxie/beego/orm"
)

type Position struct {
	Id           int64     `orm:"column(id);auto" description:"职位表id"`
	CompanyId    int64     `orm:"column(company_id)" description:"表company.id 公司编号"`
	Name         string    `orm:"column(name);size(100)" description:"职位名称"`
	ParentId     int64     `orm:"column(parent_id)" description:"父级id"`
	Relation     string    `orm:"column(relation);size(1000)" description:"父子级关系树"`
	CreateAt     time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
	UpdateAt     time.Time `orm:"column(update_at);type(timestamp)" description:"更新时间"`
	DeleteAt     time.Time `orm:"column(delete_at);type(timestamp)" description:"删除时间"`
	EnableStatus string    `orm:"column(enable_status);size(255)" description:"有效状态 1:有效 0:无效"`
	Level        int       `orm:"column(level)"`
}

//关联企业总后台的id
func (t *Position) TableName() string {
	return "position"
}

func init() {
	orm.RegisterModel(new(Position))
}

func (t *Position) SetRelation(parent *Position) error {
	// if t.Id == 0 {
	// 	return errors.New("Id==0")
	// }
	if parent == nil || t.Id == 0 {
		t.Relation = fmt.Sprintf("%d", t.Id)
	} else {
		t.Relation = fmt.Sprintf("%s/%d", parent.Relation, t.Id)
	}
	return nil
}

// AddPosition insert a new Position into database and returns
// last inserted Id on success.
func AddPosition(m *Position, om ...orm.Ormer) (id int64, err error) {
	var o orm.Ormer
	if len(om) > 0 {
		o = om[0]
	} else {
		o = orm.NewOrm()
	}
	m.CreateAt = time.Now()
	m.UpdateAt = time.Now()
	m.DeleteAt = time.Unix(0, 0)
	m.EnableStatus = "1"
	id, err = o.Insert(m)
	return
}

// GetPositionById retrieves Position by Id. Returns error if
// Id doesn't exist
func GetPositionById(id int64) (v *Position, err error) {
	o := orm.NewOrm()
	v = &Position{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdatePositionById updates Department by Id and returns error if
// the record to be updated doesn't exist
func UpdatePositionById(m *Position, col []string, om ...orm.Ormer) (err error) {
	var o orm.Ormer
	if len(om) > 0 {
		o = om[0]
	} else {
		o = orm.NewOrm()
	}
	v := Position{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		m.UpdateAt = time.Now()
		col = append(col, "UpdateAt")
		if num, err = o.Update(m, col...); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

func ExistPositiontName(companyid int64, parentId int64, dname string) bool {
	var (
		ok bool
	)
	o := orm.NewOrm()
	ok = o.QueryTable(&Position{}).
		Filter("name", dname).
		Filter("parent_id", parentId).
		Filter("company_id", companyid).
		Filter("delete_at", 0).
		Exist()
	return ok
}