我在最近的项目中经常使用sequelize,我很好奇关联与迁移的幕后情况会发生什么。例如,当我生成 2 个模型时:
user = {
id,
name,
}
和
post = {
id,
name,
}
然后我生成一个迁移以添加关联的列:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.addColumn(
'posts',
'userId', // name of the key we're adding
{
type: Sequelize.UUID,
references: {
model: 'users', // name of Target model
key: 'id', // key in Target model that we're referencing
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
}
);
},
down: (queryInterface, Sequelize) => {
return queryInterface.removeColumn(
'posts', // name of Source model
'userId' // key we want to remove
);
}
};
如果上面的迁移将实际的 userId
列添加到 posts 表中,模型中的 associate
方法会做什么?
模型中关联
方法的示例:
module.exports = (sequelize, DataTypes) => {
const post = sequelize.define('post', {
name: DataTypes.TEXT
}, {});
post.associate = function(models) {
post.belongsTo(models.user);
};
return post;
};
这提出了一个更大的问题,如果关联方法最终在数据库中创建实际的外键列,则是否需要创建外键列的中间迁移(如上面所示,创建外键列) ?
最佳答案
TL;DR: Sequelize
Associations
do not do anything on the DB side, meaning they can't (create tables, add columns, add constraints, ..etc)Disclaimer: I might've not covered all the benefits/differences of both in this answer, this just an abstract.
1) 这是我如何区分 Model
和 Migration
(基于功能):
- 数据库上的
迁移
(创建表、添加约束等) 模型
使开发人员可以更轻松地与数据库上与模型
(定义模型的对象)对应的表进行交互,例如:User
模型可帮助您与 Users 表进行交互,而无需编写 SQL 查询。
2) Associate
方法为您提供了两种特殊的功能,即 lazyLoading 和 eagerLoading他们都让您免去了通过原始 SQL 查询手动进行 Join
的麻烦。
所以,是的,再说一次:“模型让您免去了自己编写原始 SQL 查询的麻烦。”
关于javascript - 做 Sequelize 关联 在数据库端做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53979278/