我正在使用 Sequelize,一个用于 mysql 的 Nodejs ORM。使用 mysql 工作台,我制作了一个 EEM 图并将该设计推送到数据库中,到目前为止一切顺利。
现在在 Sequelize 中,我必须告诉它数据库的设计是什么样的,其中一部分是告诉它外键的名称。
在工作台中,表中有一个外键
选项卡有一些格式类似于
fd_positions_tradingPLan1`的变量,但我从未命名过,事实上在我的 EEM 图表中我有
然后,如果我转到底部的外键
选项卡,我就会得到这个。我很困惑到底应该告诉 ORM 外键是什么......
最佳答案
让我们以您的职位
表作为引用。要在sequelize上构建模型,您必须执行以下操作:
module.exports = (sequelize, DataTypes) => {
const Position = sequelize.define('Position', { // this is the name that you'll use on sequelize methods, not what you have on your db
// define your columns like this:
tradeName: { //the name of the variable that you'll use on sequelize and js
field: 'trade_name', //the actual name of your column on the table
type: DataTypes.STRING(128) // the data type
},
// .......
// for your foreignKeys you have to define the column like your other attributes.
userId: {
field: 'user_id',
type: DataTypes.INTEGER
},
}, {
tableName: 'positions', //this is the name of your table on the database
underscored: true, // to recognize the underscore names
createdAt: 'created_at', //
updatedAt: 'updated_at',
});
//now for your association let's say that you defined your USER table like this example.
Position.associate = (models) => {
// on the foreignKey value, youhave to put the same that you define above, and on the db.
Position.belongsTo(models.User, { as: 'User', foreignKey: 'user_id' });
//depending on your other relations, you are gonna use hasMany, hasOne, belongsToMany
};
return Position;
};
Sequelize 仅以一种方式进行关联,这意味着在此示例中,您无法使用从 User
到 Position
的 Sequelize 进行查询,以便能够
您必须在两个模型上定义双向关联。
User.associate = (models) => {
// on this case we use hasMany cause user can have many positions I suppose, if not, use hasOne
User.hasMany(models.Poisition, { as: 'positions', foreignKey: 'user_id' }); //remeber to use the same foreignKey name
};
更新:
as
是 Sequelize 的标识符。假设您为同一模型建立了两个关联,稍后当您尝试查询其中一个关联时,您可以指定所需的关联
User.associate = (models) => {
User.hasMany(models.Poisition, { as: 'positions', foreignKey: 'user_id' });
User.hasMany(models.Poisition, { as: 'customerPositions', foreignKey: 'customer_id' });
};
//the actual association call
User.findAll({
include:[{
model: db.user,
as: 'positions'
}, {
model: db.user,
as: 'customerPositions'
}]
})
现在对于fk_positions_users1
来说,这是MySQL本身的标识符。 Sequelize 仅检查foreignKey 和涉及的模型。显然,当 Sequelize 创建引用时,它使用表和列名称给出模板名称。我尝试自己在表上创建一个新的外键,然后更新模型,一切顺利。您应该不会有任何问题。
关于MySQL的外键名称是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55641178/