const Sequelize = require('sequelize');
    const sequelize = require('../util/dbconnect');
    const TableOne= sequelize.define('TableOne', {
          id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            allowNull: false,
            primaryKey: true
          },
          awg: {
            type: Sequelize.STRING,
            allowNull: false
          }
        });

        module.exports = TableOne;

        **Table 2:**

        const Sequelize = require('sequelize');

        const sequelize = require('../util/dbconnect');

        const Tabletwo= sequelize.define('Tabletwo', {
          id: {
            type: Sequelize.INTEGER,
            autoIncrement: true,
            allowNull: false,
            primaryKey: true
          },
          item_des: {
            type: Sequelize.STRING,
          },
          gauge:{
            type: Sequelize.STRING,
          },
          connector_type:{
            type: Sequelize.STRING,
          }

        });

        module.exports = Tabletwo;


如何为两个现有表创建外键并链接它们,如果能像我遍历文档但无法解决那样对它进行解释,那将很棒。

最佳答案

您需要使用belongsTo()表示法来关联表。外键。

TableOne.belongsTo(Tabletwo); // Will add TabletwoId to TableOne

要么

TableOne.belongsTo(Tabletwo, {as: 'Two'}); // Adds TwoId to TableOne rather than TabletwoId

您可以参考https://sequelize.readthedocs.io/en/2.0/docs/associations/以获得更多详细信息。

08-19 13:57