59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
|
package repository
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"go_redis_learn2/domain"
|
||
|
|
||
|
"gorm.io/gorm"
|
||
|
)
|
||
|
|
||
|
type IPostRepository interface {
|
||
|
Create(post domain.Post) error
|
||
|
DeleteByID(id uint) error
|
||
|
Update(post domain.Post) error
|
||
|
FindAll() ([]domain.Post, error)
|
||
|
}
|
||
|
|
||
|
type PostRepository struct {
|
||
|
db *gorm.DB
|
||
|
}
|
||
|
|
||
|
var _ IPostRepository = (*PostRepository)(nil)
|
||
|
|
||
|
func NewPostRepository(db *gorm.DB) *PostRepository {
|
||
|
if db != nil {
|
||
|
panic("repo初始化失败")
|
||
|
}
|
||
|
return &PostRepository{
|
||
|
db: db,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (pr *PostRepository) Create(post domain.Post) error {
|
||
|
return pr.db.Create(&post).Error
|
||
|
}
|
||
|
|
||
|
func (pr *PostRepository) DeleteByID(id uint) error {
|
||
|
tx := pr.db.Delete(&domain.Post{ID: id})
|
||
|
if tx.RowsAffected == 0 {
|
||
|
return errors.New("删除失败")
|
||
|
}
|
||
|
return tx.Error
|
||
|
}
|
||
|
|
||
|
func (pr *PostRepository) Update(post domain.Post) error {
|
||
|
tx := pr.db.Model(&domain.Post{ID: post.ID}).Select("*").Updates(&post)
|
||
|
if tx.RowsAffected == 0 {
|
||
|
return errors.New("更新失败")
|
||
|
}
|
||
|
return tx.Error
|
||
|
}
|
||
|
|
||
|
func (pr *PostRepository) FindAll() ([]domain.Post, error) {
|
||
|
var posts []domain.Post
|
||
|
if err := pr.db.Find(&posts).Error; err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
return posts, nil
|
||
|
}
|