func (c *Category) FindCategoryOrCreate(params map[string]interface{}) *gorm.DB { sess := db.Connection().First(c, params) if c.Id == 0 { if title, ok := params["title"]; ok { c.Title = title.(string) c.Slug = title.(string) c.UserId = db.USERID } if ctype, ok := params["type"]; ok { c.Type = ctype.(string) } sess = c.Save() } return sess }
func (c *ListItemCommand) Run() error { // find category by title category := &models.Category{} if c.CategoryTitle != "" { err := category.FindByParams(map[string]interface{}{"title": c.CategoryTitle}).Error if err == nil { return errors.New("Undefine Category") } } // find all items items := []models.Item{} params := map[string]interface{}{"type": c.ItemType, "user_id": db.USERID} if category.Id != 0 { params["category_id"] = category.Id } db.Connection().Find(&items, params) // prepare table view data := [][]string{} for _, item := range items { data = append(data, []string{ strconv.Itoa(item.Id), strconv.FormatFloat(item.Amount, 'f', 2, 64), item.GetCategoryTitle(), item.Comment, }) } table := tablewriter.NewWriter(os.Stdout) table.SetHeader([]string{"Id", "Amount", "Category", "Comments"}) table.SetAlignment(tablewriter.ALIGN_LEFT) for _, v := range data { table.Append(v) } // render table views color.Println("@gSpent items:") table.Render() return nil }
func SumAmountByType(userId int, itemType string) (float64, error) { var amount float64 row := db.Connection().Table("item").Select("SUM(amount) as sumamount").Where("user_id=? AND type=?", userId, itemType).Row() row.Scan(&amount) return amount, nil }
func (i *Item) FindByParams(params map[string]interface{}) *gorm.DB { sess := db.Connection().First(i, params) return sess }
func (i *Item) Delete() *gorm.DB { return db.Connection().Delete(i) }
func (i *Item) Find(id int) *gorm.DB { return db.Connection().First(i, id) }
func (i *Item) Save() *gorm.DB { return db.Connection().Save(i) }
func (u *User) Find(id int) { db.Connection().First(u, id) }
func (u *User) Save() { db.Connection().Save(u) }
func (c *Category) FindByParams(params map[string]interface{}) *gorm.DB { sess := db.Connection().First(c, params) return sess }
func (c *Category) Delete() *gorm.DB { return db.Connection().Delete(c) }
func (c *Category) Find(id int) *gorm.DB { return db.Connection().First(c, id) }
func (c *Category) Save() *gorm.DB { return db.Connection().Save(c) }