Sequelize 模型引用 vs 关联 [英] Sequelize model references vs associations
问题描述
刚开始使用 Sequelize 并且我已经设置了一堆模型和种子,但我无法弄清楚引用与关联.如果他们甚至按照我认为的那样做,我就看不到引用的用例,但我在文档中找不到很好的解释.
Just starting to use Sequelize and I've setup a bunch of models and seeds, but I can't figure out references vs associations. I don't see the use case for references if they even do what I think they do, but I couldn't find a good explanation in the docs.
引用和关联是多余的吗?
Is this redundant having references and associations?
module.exports = (sequelize, DataTypes) => {
const UserTask = sequelize.define('UserTask',
{
id: {
primaryKey: true,
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4
},
userId: {
type: DataTypes.UUID,
references: { // <--- is this redundant to associate
model: 'User',
key: 'id'
}
}
// ... removed for brevity
},
{
classMethods: {
associate: models => { <--- makes references redundant?
UserTask.belongsTo(models.User, {
onDelete: 'CASCADE',
foreignKey: {
fieldName: 'userId',
allowNull: true,
require: true
},
targetKey: 'id'
});
}
}
}
);
return UserTask;
};
推荐答案
使用 references
可以创建对另一个表的引用,而无需添加任何约束或关联.这意味着这只是一种通知数据库该表引用另一个表的方式.
Using references
you create a reference to another table, without adding any constraints, or associations. Which means that is just a way of signaling the database that this table has a reference to another.
创建一个 association
将向属性添加外键约束.您可以执行关联功能背后的所有魔法.即 User.getTasks();
Creating an association
will add a foreign key constraint to the attributes. And the you can perform all the magic behind it the association functions. i.e User.getTasks();
有关 references
的更多信息,请访问:https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1
More info about references
here: https://sequelize.readthedocs.io/en/latest/docs/associations/#foreign-keys_1
关于 association
在这里:http://docs.sequelizejs.com/manual/tutorial/associations.html
这篇关于Sequelize 模型引用 vs 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!