MySQL外键名称是什么?

时间:2019-04-11 21:07:02

标签: mysql sequelize.js

我正在使用Sequelize,它是mysql的nodejs ORM。到目前为止,到目前为止,我使用mysql workbench制作了一个EEM图并将该设计推入数据库。

现在在Sequelize中,我必须告诉它数据库的设计是什么样的,其中一部分就是告诉它调用什么外键。

在工作台中,表foreign key fd_positions_tradingPLan1`中有一个there are variables formatted like标签,但我从不说出来,实际上在我的EEM图中

enter image description here

然后,如果我转到底部的foreign keys标签,则会看到此信息。我对应该告诉ORM外键到底是什么感到困惑。

enter image description here

1 个答案:

答案 0 :(得分:1)

让我们以您的positions表作为参考。要基于续集构建模型,您必须执行以下操作:

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仅以一种方式进行关联,这意味着在此示例中,您无法使用从UserPosition的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,然后更新模型,一切正常。你应该不会有问题的。