MySQL的外键名称是什么呢?

问题描述 投票:0回答:1

我正在使用Sequelize,一个用于mysql的nodejs ORM。使用mysql工作台我制作了一个EEM图并将该设计推送到db中,到目前为止一直很好。

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

在Workbench中,tableforeign keyfd_positions_tradingPLan1中有一个there are variables formatted like选项卡,但我从来没有说过,实际上在我的EEM图中我有

enter image description here

然后,如果我去底部的foreign keys标签,我得到这个。我很困惑,我应该告诉ORM外键是什么......

enter image description here

mysql sequelize.js
1个回答
1
投票

我们以您的positions表作为参考。要在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中的sequelize查询到Position,以便能够在两个模型上进行双向关联。

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
};

更新:

qazxsw poi是Sequelize的标识符。假设您为同一模型创建了两个关联,稍后当您尝试查询其中一个关联时,可以指定所需的关联

as

现在对于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' }] }) 来说,这是MySQL本身的标识符。 Sequelize只检查foreignKey和涉及的模型。显然,当Sequelize创建引用时,它使用表和列名称给出模板名称。我试着在桌面上创建一个新的foreignKey,然后更新模型,一切都很顺利。你不应该有这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.