go-todo-api/repositories/gorm_todo_repository.go
2025-12-02 18:58:25 +08:00

73 lines
2.1 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package repositories
import (
"go-todo-api/models"
"gorm.io/gorm"
)
// GormTodoRepository 结构体持有数据库连接,用于实现 TodoRepository 接口
type GormTodoRepository struct {
DB *gorm.DB
}
// NewGormTodoRepository 实例化一个新的 GORM 仓库
func NewGormTodoRepository(db *gorm.DB) *GormTodoRepository {
return &GormTodoRepository{DB: db}
}
// ❗ 修正 FindAll接收 userID并添加 WHERE 约束
func (r *GormTodoRepository) FindAll(userID uint) ([]models.Todo, error) {
var todos []models.Todo
// 增加 WHERE UserID = ? 约束
result := r.DB.Where("user_id = ?", userID).Find(&todos)
return todos, result.Error
}
// ❗ 修正 FindByID接收 userID并添加 WHERE 约束
// ❗ 必须确保这个方法使用了 UserID 来查找和授权
func (r *GormTodoRepository) FindByID(id uint, userID uint) (*models.Todo, error) {
var todo models.Todo
// 增加 WHERE ID = ? AND UserID = ? 约束
// ⭐ 核心WHERE id = ? AND user_id = ? 约束
result := r.DB.Where("id = ? AND user_id = ?", id, userID).First(&todo)
if result.Error != nil {
return nil, result.Error
}
return &todo, nil
}
// ❗ 修正 Create 方法签名
func (r *GormTodoRepository) Create(todo *models.Todo) error {
if result := r.DB.Create(todo); result.Error != nil {
return result.Error
}
return nil
}
// ❗ 修正 Delete接收 userID并添加 WHERE 约束
func (r *GormTodoRepository) Delete(id uint, userID uint) error {
var todo models.Todo
// 增加 WHERE ID = ? AND UserID = ? 约束
result := r.DB.Where("id = ? AND user_id = ?", id, userID).Delete(&todo)
if result.Error != nil {
return result.Error
}
// 如果没有行受到影响,且没有错误,说明记录未找到(或不属于该用户)
if result.RowsAffected == 0 {
return gorm.ErrRecordNotFound
}
return nil
}
// ❗ 修正 Update 方法签名
func (r *GormTodoRepository) Update(todo *models.Todo, input map[string]interface{}) error {
// GORM 的 Updates 方法可以更新 map 中的字段
if result := r.DB.Model(todo).Updates(input); result.Error != nil {
return result.Error
}
return nil
}