我有一个User
模型,主键为id
。我目前正在为Supervisor建模>与名为user_supervisors
的排序连接表的用户关系,其中只有两列user_id
和supervisor_id
,这两列都是引用User
记录主键的外键。
当我删除用户(无论他们是否是主管)时,是否有可能删除user_supervisors
表中包含该用户的任何记录?
我一直在尝试使用sql server的级联删除,但似乎不可能同时对user_id和supervisor_id外键进行级联删除。我总是遇到一条消息:
Knex:警告 - 迁移失败,错误:CREATE TABLE [user_supervisors]([user_id] int,[supervisor_id] int,CONSTRAINT [user_supervisors_pkey] PRIMARY KEY([user_id],[supervisor_id]),CONSTRAINT [user_supervisors_user_id_foreign] FOREIGN KEY ([user_id])REFERENCES [users]([id])ON DELETE CASCADE,CONSTRAINT [user_supervisors_supervisor_id_foreign] FOREIGN KEY([supervisor_id])REFERENCES [users]([id])ON DELETE CASCADE) - 无法创建约束或索引。查看以前的错误。
对于记录,我使用knex来运行数据库迁移 下面是创建上述每个表时使用的SQL:
CREATE TABLE [users]
(
[id] int identity(1,1) not null primary key
, [created_at] datetime
, [updated_at] datetime
, [email] nvarchar(255) not null
, [first_name] nvarchar(255)
, [last_name] nvarchar(255)
, [password] nvarchar(255) not null
, [company_id] int
, CONSTRAINT [users_email_unique] UNIQUE ([email])
, CONSTRAINT [users_company_id_foreign] FOREIGN KEY ([company_id]) REFERENCES [companies] ([id]) ON DELETE CASCADE
)
CREATE TABLE [user_supervisors]
(
[user_id] int
, [supervisor_id] int
, CONSTRAINT [user_supervisors_pkey] PRIMARY KEY ([user_id], [supervisor_id])
, CONSTRAINT [user_supervisors_user_id_foreign] FOREIGN KEY ([user_id]) REFERENCES [users] ([id]) ON DELETE CASCADE
, CONSTRAINT [user_supervisors_supervisor_id_foreign] FOREIGN KEY ([supervisor_id]) REFERENCES [users] ([id])
)