50 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			50 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| // Package repository 提供了数据访问的仓库实现
 | |
| package repository
 | |
| 
 | |
| import (
 | |
| 	"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
 | |
| 	"gorm.io/gorm"
 | |
| )
 | |
| 
 | |
| // UserRepository 定义了与用户模型相关的数据库操作接口
 | |
| // 这是为了让业务逻辑层依赖于抽象,而不是具体的数据库实现
 | |
| type UserRepository interface {
 | |
| 	Create(user *models.User) error
 | |
| 	FindByUsername(username string) (*models.User, error)
 | |
| 	FindByID(id uint) (*models.User, error)
 | |
| }
 | |
| 
 | |
| // gormUserRepository 是 UserRepository 的 GORM 实现
 | |
| type gormUserRepository struct {
 | |
| 	db *gorm.DB
 | |
| }
 | |
| 
 | |
| // NewGormUserRepository 创建一个新的 UserRepository GORM 实现实例
 | |
| func NewGormUserRepository(db *gorm.DB) UserRepository {
 | |
| 	return &gormUserRepository{db: db}
 | |
| }
 | |
| 
 | |
| // Create 创建一个新的用户记录
 | |
| func (r *gormUserRepository) Create(user *models.User) error {
 | |
| 	// BeforeSave 钩子会在这里被自动触发
 | |
| 	return r.db.Create(user).Error
 | |
| }
 | |
| 
 | |
| // FindByUsername 根据用户名查找用户
 | |
| func (r *gormUserRepository) FindByUsername(username string) (*models.User, error) {
 | |
| 	var user models.User
 | |
| 	if err := r.db.Where("username = ?", username).First(&user).Error; err != nil {
 | |
| 		return nil, err
 | |
| 	}
 | |
| 	return &user, nil
 | |
| }
 | |
| 
 | |
| // FindByID 根据 ID 查找用户
 | |
| func (r *gormUserRepository) FindByID(id uint) (*models.User, error) {
 | |
| 	var user models.User
 | |
| 	if err := r.db.First(&user, id).Error; err != nil {
 | |
| 		return nil, err
 | |
| 	}
 | |
| 	return &user, nil
 | |
| }
 |