spark-server/internal/module/user/model/user_email.go
2026-09-23 17:11:56 +08:00

51 lines
1.4 KiB
Go
Raw 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 model
import (
"context"
"time"
"gorm.io/gorm"
"spark-server/internal/module/user/entity"
)
// UserEmail maps table user_emails: one normalized email to one user.
type UserEmail struct {
ID int64 `gorm:"column:id;primaryKey;autoIncrement;comment:行 id,表内自增,仅内部用;业务唯一键是 email"`
Email string `gorm:"column:email;comment:规范化后的小写邮箱,登录账号"`
UserID int64 `gorm:"column:user_id;comment:绑定的 users.id,一对一"`
CreatedAt time.Time `gorm:"column:created_at;comment:绑定时间"`
}
func (UserEmail) TableName() string { return "t_user_emails" }
func (m *Repo) GetByEmail(ctx context.Context, email string) (*entity.User, error) {
db, err := m.session(ctx)
if err != nil {
return nil, err
}
var bind UserEmail
if err := db.Where("email = ?", email).Take(&bind).Error; err != nil {
return nil, mapDBErr(err)
}
return m.GetByID(ctx, bind.UserID)
}
func (m *Repo) CreateWithEmail(ctx context.Context, u *entity.User, email string) error {
db, err := m.session(ctx)
if err != nil {
return err
}
return db.Transaction(func(tx *gorm.DB) error {
row := fromEntity(u)
if err := tx.Create(&row).Error; err != nil {
return mapDBErr(err)
}
bind := UserEmail{Email: email, UserID: u.ID, CreatedAt: u.CreatedAt}
if err := tx.Create(&bind).Error; err != nil {
return mapDBErr(err)
}
return nil
})
}