Sequelize 复合外键 [英] Sequelize Composite Foreign Key
本文介绍了Sequelize 复合外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下表格的数据库:
I have a database with the following tables:
CREATE TABLE IF NOT EXISTS `app_user` (
`user_id` INT NOT NULL,
`user_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`user_id`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `user_folder` (
`user_id` INT NOT NULL,
`document_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `document_id`),
CONSTRAINT `fk_user_document_user`
FOREIGN KEY (`user_id`)
REFERENCES `zinc`.`app_user` (`user_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `folder_content` (
`user_id` INT NOT NULL,
`document_id` INT NOT NULL,
`content_id` INT NOT NULL,
PRIMARY KEY (`user_id`, `document_id`, `content_id`),
CONSTRAINT `fk_folder_content_folder`
FOREIGN KEY (`user_id` , `document_id`)
REFERENCES `zinc`.`user_folder` (`user_id` , `document_id`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
我需要创建一个 Sequelize 模型来表示它.我唯一的问题是关系 folder_content 和 user_folder 因为复合键.
I need to create a Sequelize model to represent it. The only problem I have is with the relation folder_content and user_folder because of the composite key.
如何创建此续集模型?
这是我目前所拥有的:
var AppUser = sequelize.define('app_user',
{userId: {type: Sequelize.INTEGER, primaryKey: true, field: 'user_id'}, ... } );
var UserFolder = sequelize.define('user_folder',
{userId: {type: Sequelize.INTEGER, primaryKey: true, field: 'user_id'},
documentId: {type: Sequelize.INTEGER, primaryKey: true, field: 'document_id'}... });
var FolderContent = sequelize.define('folder_content', {
userId: {type: Sequelize.INTEGER, primaryKey: true, field: 'user_id'},
documentId: {type: Sequelize.INTEGER, primaryKey: true, field: 'document_id'},
contentId: {type: Sequelize.INTEGER, primaryKey: true, field: 'content_id'}... });
UserFolder.hasMany(FolderContent);
FolderContent.belongsTo(UserFolder, {foreingKey: !! });// <- PROBLEM
推荐答案
sequelize 还不支持复合外键吗?我想要一个带有 2 个外键的表作为复合主键.我宁愿采用这种方式,也不愿将代理键作为主键,并在 2 个外键字段上具有唯一约束.
does sequelize still not support composite foreign keys? i would like to have a table with 2 foreign keys as the composite primary key. i would rather have it this way than have a surrogate key as the primary key with a unique constraint over the 2 foreign key fields.
谢谢
这篇关于Sequelize 复合外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文