56 lines
1.5 KiB
Go
56 lines
1.5 KiB
Go
package models
|
|
|
|
import (
|
|
"github.com/shopspring/decimal"
|
|
"gorm.io/gorm"
|
|
"time"
|
|
)
|
|
|
|
type Product struct {
|
|
ID string `gorm:"size:36;not null;uniqueIndex;primary_key"`
|
|
ParentID string `gorm:"size:36;index"`
|
|
Name string `gorm:"size:255"`
|
|
Slug string `gorm:"size:255"`
|
|
ProductImages []ProductImage
|
|
Price decimal.Decimal `gorm:"type:decimal(16,2);"`
|
|
Categories []Category `gorm:"many2many:product_categories;"`
|
|
ShortDescription string `gorm:"type:text"`
|
|
Description string `gorm:"type:text"`
|
|
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
DeletedAt gorm.DeletedAt
|
|
}
|
|
|
|
func (p *Product) GetProducts(db *gorm.DB, perPage int, page int) (*[]Product, int64, error) {
|
|
|
|
var count int64
|
|
var products []Product
|
|
|
|
err := db.Debug().Model(&Product{}).Count(&count).Error
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
offset := (page - 1) * perPage
|
|
|
|
err = db.Debug().Model(&Product{}).Order("created_at desc").Limit(perPage).Offset(offset).Find(&products).Error
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return &products, count, nil
|
|
}
|
|
|
|
func (p *Product) FindByID(db *gorm.DB, productID string) (*Product, error) {
|
|
var err error
|
|
var product Product
|
|
|
|
err = db.Debug().Preload("ProductImages").Model(&Product{}).Where("id = ?", productID).First(&product).Error
|
|
//err = db.Debug().Model(&Product{}).Where("id = ?", productID).First(&product).Error
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &product, nil
|
|
}
|