组合复合外键 [英] Sequelize Composite Foreign Key
本文介绍了组合复合外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含以下表格的数据库:
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.
如何创建这个续集模型?
How can I create this sequelize model?
这是我到目前为止所拥有的:
This is what I have so far:
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不支持复合外键.这会带来一些问题.
Now Sequelize doesn't support composite foreign keys. This creates several problems.
- 当Sequelize创建表时,表定义没有复合FK.
为了解决这个问题,我在模型和函数上使用了afterSync
钩子 如果表中不存在FK,则会将其添加到表中. 示例代码. - 当我将
findAll
方法用于include
这样的模型时,我使用findAll
方法的include[].on
选项.或者,如果您不使用我那么多的联接,则可以在创建关联时使用scope
(请参阅).
- When Sequelize creates a table, the table definition does not have a composite FK.
To solve this problem I use theafterSync
hook on the model and a function that adds a FK to the table if it does not exist. Example code. - When I use the
findAll
method withinclude
such model, I use theinclude[].on
option of thefindAll
method. Or if you don't use as many joins as I do, you can usescope
when creating an association (see).
这篇关于组合复合外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文