init project
This commit is contained in:
53
internal/repositories/product_repository.go
Normal file
53
internal/repositories/product_repository.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"github.com/dungnt11/senflow_app/internal/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ProductRepository triển khai IProductRepository
|
||||
type ProductRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewProductRepository tạo một instance mới của ProductRepository
|
||||
func NewProductRepository(db *gorm.DB) *ProductRepository {
|
||||
return &ProductRepository{
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
|
||||
// Create tạo một sản phẩm mới
|
||||
func (r *ProductRepository) Create(product *models.Product) error {
|
||||
return r.db.Create(product).Error
|
||||
}
|
||||
|
||||
// FindByID tìm sản phẩm theo ID
|
||||
func (r *ProductRepository) FindByID(id uint) (*models.Product, error) {
|
||||
var product models.Product
|
||||
err := r.db.First(&product, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &product, nil
|
||||
}
|
||||
|
||||
// FindAll lấy tất cả sản phẩm
|
||||
func (r *ProductRepository) FindAll() ([]*models.Product, error) {
|
||||
var products []*models.Product
|
||||
err := r.db.Find(&products).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return products, nil
|
||||
}
|
||||
|
||||
// Update cập nhật thông tin sản phẩm
|
||||
func (r *ProductRepository) Update(product *models.Product) error {
|
||||
return r.db.Save(product).Error
|
||||
}
|
||||
|
||||
// Delete xóa sản phẩm theo ID
|
||||
func (r *ProductRepository) Delete(id uint) error {
|
||||
return r.db.Delete(&models.Product{}, id).Error
|
||||
}
|
||||
Reference in New Issue
Block a user