在连接表的任一侧启用级联删除

时间:2018-05-25 19:39:20

标签: sql-server foreign-keys sql-delete cascade knex.js

我有一个User模型,主键为id。我目前正在为Supervisor建模>与名为user_supervisors的排序连接表的用户关系,其中只有两列user_idsupervisor_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])
)

0 个答案:

没有答案