company.go 2.8 KB
package models

import (
	"fmt"
	"time"

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

type Company struct {
	Id           int64     `orm:"column(id);auto"`
	Name         string    `orm:"column(name);size(40)"`
	AdminId      int64     `orm:"column(admin_id)"`
	CreateAt     time.Time `orm:"column(create_at);type(timestamp);auto_now"`
	UpdateAt     time.Time `orm:"column(update_at);type(timestamp)"`
	DeleteAt     time.Time `orm:"column(delete_at);type(timestamp)"`
	Logo         string    `orm:"column(logo);size(255)"`
	Enable       int8      `orm:"column(enable)"`
	UserCenterId int64     `orm:"column(user_center_id)"`
}

func (t *Company) TableName() string {
	return "company"
}

//公司是否有效
const (
	COMPANY_ENABLE_YES int8 = 1 //有效
	COMPANY_ENABLE_NO  int8 = 2 //无效
)

func (t *Company) IsEnable() bool {
	switch t.Enable {
	case COMPANY_ENABLE_YES:
		return true
	case COMPANY_ENABLE_NO:
		return false
	}
	return false
}

func (t *Company) ValidateEnable(v int8) bool {
	switch v {
	case COMPANY_ENABLE_YES:
		return true
	case COMPANY_ENABLE_NO:
		return true
	}
	return false
}
func init() {
	orm.RegisterModel(new(Company))
}

// AddCompany insert a new Company into database and returns
// last inserted Id on success.
func AddCompany(m *Company, 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.Enable = COMPANY_ENABLE_YES
	m.DeleteAt = time.Unix(0, 0)
	id, err = o.Insert(m)
	return
}

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

// UpdateCompany updates Company by Id and returns error if
// the record to be updated doesn't exist
func UpdateCompanyById(m *Company, col []string, om ...orm.Ormer) (err error) {
	var o orm.Ormer
	if len(om) > 0 {
		o = om[0]
	} else {
		o = orm.NewOrm()
	}
	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 GetCompanyByUser(userid int64) ([]Company, error) {
	datasql := `SELECT a.user_id, a.id,a.name,a.logo,a.admin_id FROM company AS a
			JOIN user_company AS b ON a.id = b.company_id
			WHERE a.enable = 1 AND b.user_id=?`
	var (
		err      error
		companys []Company
	)
	o := orm.NewOrm()
	_, err = o.Raw(datasql).QueryRows(&companys)
	if err == orm.ErrNoRows {
		return companys, nil
	}
	return companys, err
}

func GetCompanyByUCenter(uCenterId int64) (*Company, error) {
	var (
		err error
	)
	data := &Company{}
	o := orm.NewOrm()
	err = o.QueryTable(&Company{}).
		Filter("user_center_id", uCenterId).
		One(data)
	return data, err
}