dosequelize关联在DB方面做任何事情



我在最近的项目中使用了很多sequelize,我很好奇关联与迁移的背后会发生什么。例如,当我生成两个模型时:

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方法会做什么?

模型中associate方法的示例:

module.exports = (sequelize, DataTypes) => {
const post = sequelize.define('post', {
name: DataTypes.TEXT
}, {});
post.associate = function(models) {
post.belongsTo(models.user);
};
return post;
};

这就提出了一个更大的问题,如果associate方法最终在数据库中创建了实际的外键列,那么创建外键列是否需要中间迁移(如上面显示的创建外键列的迁移)?

TL;DR:SequelizeAssociations在DB端不做任何事情,这意味着它们不能(创建表、添加列、添加约束等)

免责声明:我可能没有涵盖两者在这个答案中,这只是一个抽象。

1)以下是如何区分ModelMigration(基于功能):

  • 数据库上的Migration(创建表、添加约束等)
  • Model使开发人员更容易与数据库上与Model(为其定义的模型)对应的表进行交互,例如:User模型可帮助您与Users表进行交互而无需编写SQL查询

2)Associate方法为您提供了两种特殊的功能,即lazyLoading和eagerLoading,它们都可以让您省去通过原始SQL查询手动执行Joins的麻烦
所以是的:"模型让您不用自己编写原始SQL查询了。">

尽管这并不能完全回答这个问题的细节,但在关联文件夹下的sequelize github repo中有一个关于关联的不错的描述

评论指出:

创建关联将为属性添加外键约束

此外,以下提示了列实际上是从关联中生成的:

* To get full control over the foreign key column added by sequelize,
* you can use the `foreignKey` option. It can either be a string, 
* that specifies the name, or and object type definition,
* equivalent to those passed to `sequelize.define`.
*
* ```js
* User.hasMany(Picture, { foreignKey: 'uid' })
* ```
*
* The foreign key column in Picture will now be called `uid` 
* instead of the default `userId`.
*
* ```js
* User.hasMany(Picture, {
*   foreignKey: {
*     name: 'uid',
*     allowNull: false
*   }
* })
* ```

最新更新