You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法使用Sequelize实现指定外键关联配置的技术求助

问题:在Sequelize中实现客户与套餐的外键关联及删除限制

需求说明

数据库需包含多个可被多客户共用的套餐(plans),每个客户同一时间仅能关联一个套餐(类似订阅模式)。原生SQL可实现该关联逻辑,并限制无法删除至少关联一个客户的套餐,但目前无法在Sequelize中重现此外键设置。

原生SQL实现(DDL片段)

CREATE TABLE customers (
  id int NOT NULL AUTO_INCREMENT,
  planId int,
  PRIMARY KEY (id)
)
CREATE TABLE plans (
  planId int NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (planId) 
)
ADD CONSTRAINT FK_customers_planId FOREIGN KEY (planId)
REFERENCES plans (planId);

尝试情况

已阅读Sequelize 6版本文档的关联创建及高级关联章节,尝试过hasOne、belongsTo、belongsToMany及through选项等(已知through用于创建关联表,仅作测试),但均无法实现上述SQL的效果。尝试代码如下:

db.Plans.User = db.Plans.belongsTo(db.Customer);
db.Customer.Plans = db.Customer.hasOne(db.Plans, { foreignKey: db.Plans.planId });
db.Plans.belongsToMany(db.Customer, { through: 'customerplans' });
db.Customer.hasOne(db.Plans, { through: 'customerplans' });

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:20:27