You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

83 lines
2.2 KiB

package model
import (
"context"
"errors"
"gorm.io/gorm"
)
// FileInsert 插入文件记录
func FileInsert(ctx context.Context, db *gorm.DB, file *File) (int64, error) {
result := db.WithContext(ctx).Create(file)
if result.Error != nil {
return 0, result.Error
}
return file.Id, nil
}
// FileFindOne 根据 ID 查询文件
func FileFindOne(ctx context.Context, db *gorm.DB, id int64) (*File, error) {
var file File
result := db.WithContext(ctx).Where("status = 1").First(&file, id)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, ErrNotFound
}
return nil, result.Error
}
return &file, nil
}
// FileFindList 查询文件列表(分页+筛选+权限)
func FileFindList(ctx context.Context, db *gorm.DB, page, pageSize int64, keyword, category, mimeType string, userId int64, userRole string) ([]File, int64, error) {
var files []File
var total int64
query := db.WithContext(ctx).Model(&File{}).Where("status = 1")
// 权限过滤:非 admin/super_admin 只能看自己的文件 + 公开文件
if userRole != RoleAdmin && userRole != RoleSuperAdmin {
query = query.Where("user_id = ? OR is_public = ?", userId, true)
}
if keyword != "" {
query = query.Where("name LIKE ?", "%"+keyword+"%")
}
if category != "" {
query = query.Where("category = ?", category)
}
// MIME 类型前缀匹配(如 "image" 匹配 "image/png")
if mimeType != "" {
query = query.Where("mime_type LIKE ?", mimeType+"%")
}
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
offset := (page - 1) * pageSize
if offset < 0 {
offset = 0
}
err := query.Order("created_at DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&files).Error
if err != nil {
return nil, 0, err
}
return files, total, nil
}
// FileUpdate 更新文件记录
func FileUpdate(ctx context.Context, db *gorm.DB, file *File) error {
result := db.WithContext(ctx).Save(file)
return result.Error
}
// FileDelete 软删除文件(设置 status=0)
func FileDelete(ctx context.Context, db *gorm.DB, id int64) error {
result := db.WithContext(ctx).Model(&File{}).Where("id = ?", id).Update("status", 0)
return result.Error
}