diff --git a/backend/shared/models/account.py b/backend/shared/models/account.py index 35a62cc..1688fa7 100644 --- a/backend/shared/models/account.py +++ b/backend/shared/models/account.py @@ -24,7 +24,7 @@ class Account(Base): user = relationship("User", back_populates="accounts") tasks = relationship("Task", back_populates="account", cascade="all, delete-orphan") - signin_logs = relationship("SigninLog", back_populates="account") + signin_logs = relationship("SigninLog", back_populates="account", cascade="all, delete-orphan", passive_deletes=True) def __repr__(self): return f"" diff --git a/backend/shared/models/signin_log.py b/backend/shared/models/signin_log.py index 1100fd0..7ad4cbc 100644 --- a/backend/shared/models/signin_log.py +++ b/backend/shared/models/signin_log.py @@ -10,7 +10,7 @@ from .base import Base class SigninLog(Base): __tablename__ = "signin_logs" id = Column(Integer, primary_key=True, autoincrement=True) - account_id = Column(String(36), ForeignKey("accounts.id"), nullable=False) + account_id = Column(String(36), ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False) topic_title = Column(String(100)) status = Column(String(50), nullable=False) reward_info = Column(JSON, nullable=True) diff --git a/init-db.sql b/init-db.sql index 5f7d5bc..f1771f4 100644 --- a/init-db.sql +++ b/init-db.sql @@ -59,7 +59,7 @@ CREATE TABLE IF NOT EXISTS signin_logs ( INDEX idx_signin_logs_account_id (account_id), INDEX idx_signin_logs_signed_at (signed_at), INDEX idx_signin_logs_status (status), - FOREIGN KEY (account_id) REFERENCES accounts(id) + FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- Invite codes table diff --git a/migrate_fix_signin_logs_fk.sql b/migrate_fix_signin_logs_fk.sql new file mode 100644 index 0000000..7df3841 --- /dev/null +++ b/migrate_fix_signin_logs_fk.sql @@ -0,0 +1,21 @@ +-- 修复 signin_logs 外键:删除账号时级联删除签到记录 +-- 用法: mysql -u weibo -p123456 weibo_hotsign < migrate_fix_signin_logs_fk.sql + +-- 先查出旧外键名并删除,再重建 +SET @fk_name = ( + SELECT CONSTRAINT_NAME FROM information_schema.KEY_COLUMN_USAGE + WHERE TABLE_SCHEMA = 'weibo_hotsign' + AND TABLE_NAME = 'signin_logs' + AND COLUMN_NAME = 'account_id' + AND REFERENCED_TABLE_NAME = 'accounts' + LIMIT 1 +); + +SET @sql = CONCAT('ALTER TABLE signin_logs DROP FOREIGN KEY ', @fk_name); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +ALTER TABLE signin_logs + ADD CONSTRAINT fk_signin_logs_account + FOREIGN KEY (account_id) REFERENCES accounts(id) ON DELETE CASCADE;