Sequelize.js 使用外键时,获取;用户.DepartmentDepartmentId“;而不是",;用户.部门ID“;

Sequelize.js 使用外键时,获取;用户.DepartmentDepartmentId“;而不是",;用户.部门ID“;,sequelize.js,sequelize-cli,Sequelize.js,Sequelize Cli,在尝试使用Sequelize cli/js重新创建数据库结构时,我在使用外键连接表时遇到了奇怪的行为。它似乎在外键中添加模型名称,即使我专门指定了外键。方言是MSSQL 用户模型 module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { UserId: { type: DataTypes.INTEGER, allowNull: false,

在尝试使用Sequelize cli/js重新创建数据库结构时,我在使用外键连接表时遇到了奇怪的行为。它似乎在外键中添加模型名称,即使我专门指定了外键。方言是MSSQL

用户模型

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    UserId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    FirstName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    LastName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    Email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    OfficePhone: {
      type: DataTypes.STRING
    },
    DepartmentId: {
      type: DataTypes.INTEGER
    },
    ContractorId: {
      type: DataTypes.INTEGER
    },
    IsActive: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppUsers',
    indexes: [
      {
        unique: true,
        fields: ['Username']
      }
    ]
  });
  User.associate = function(models) {
    User.belongsTo(models.Department, {
      targetKey: 'DepartmentId'
    });
    User.belongsTo(models.Contractor, {
      targetKey: 'ContractorId'
    });
  };
  return User;
};
  const Department = sequelize.define('Department', {
    DepartmentId: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    DepartmentName: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppDepartments',
    indexes: [
      {
        unique: true,
        fields: ['DepartmentName']
      }
    ]
  });
  Department.associate = function(models) {
    Department.hasMany(models.User, {
      foreignKey: 'DepartmentId'
    });
  };
  return Department;
};
exports.getUsers = async (req, res, next) => {
  const showDeleted = ( req.headers.showdeleted == 'false' ); 
  await User.findAll({
    attributes: ['UserId', 'FirstName', 'LastName', 'Username', 'Email', 'OfficePhone', 'IsActive', 'DeletedAt'],
    include: [
      { model: Department, attributes: ['DepartmentName'] },
      { model: Contractor, attributes: ['ContractorName'] }
    ],
    paranoid: showDeleted,
    order: [
      ['LastName', 'ASC']
    ]
  })
    .then(results => {
      res.status(200).send(results);
    })
    .catch(err => {
      console.log(err);
    })
};
部门模式

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    UserId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    FirstName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    LastName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    Email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    OfficePhone: {
      type: DataTypes.STRING
    },
    DepartmentId: {
      type: DataTypes.INTEGER
    },
    ContractorId: {
      type: DataTypes.INTEGER
    },
    IsActive: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppUsers',
    indexes: [
      {
        unique: true,
        fields: ['Username']
      }
    ]
  });
  User.associate = function(models) {
    User.belongsTo(models.Department, {
      targetKey: 'DepartmentId'
    });
    User.belongsTo(models.Contractor, {
      targetKey: 'ContractorId'
    });
  };
  return User;
};
  const Department = sequelize.define('Department', {
    DepartmentId: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    DepartmentName: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppDepartments',
    indexes: [
      {
        unique: true,
        fields: ['DepartmentName']
      }
    ]
  });
  Department.associate = function(models) {
    Department.hasMany(models.User, {
      foreignKey: 'DepartmentId'
    });
  };
  return Department;
};
exports.getUsers = async (req, res, next) => {
  const showDeleted = ( req.headers.showdeleted == 'false' ); 
  await User.findAll({
    attributes: ['UserId', 'FirstName', 'LastName', 'Username', 'Email', 'OfficePhone', 'IsActive', 'DeletedAt'],
    include: [
      { model: Department, attributes: ['DepartmentName'] },
      { model: Contractor, attributes: ['ContractorName'] }
    ],
    paranoid: showDeleted,
    order: [
      ['LastName', 'ASC']
    ]
  })
    .then(results => {
      res.status(200).send(results);
    })
    .catch(err => {
      console.log(err);
    })
};
全部查找

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    UserId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    FirstName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    LastName: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    Email: {
      type: DataTypes.STRING,
      allowNull: false
    },
    Password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    OfficePhone: {
      type: DataTypes.STRING
    },
    DepartmentId: {
      type: DataTypes.INTEGER
    },
    ContractorId: {
      type: DataTypes.INTEGER
    },
    IsActive: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 1
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppUsers',
    indexes: [
      {
        unique: true,
        fields: ['Username']
      }
    ]
  });
  User.associate = function(models) {
    User.belongsTo(models.Department, {
      targetKey: 'DepartmentId'
    });
    User.belongsTo(models.Contractor, {
      targetKey: 'ContractorId'
    });
  };
  return User;
};
  const Department = sequelize.define('Department', {
    DepartmentId: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    DepartmentName: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true
    },
    CreatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    UpdatedAt: {
      allowNull: false,
      type: DataTypes.DATE
    },
    DeletedAt: {
      type: DataTypes.DATE
    }
  }, {
    paranoid: true,
    timestamps: true,
    createdAt: 'CreatedAt',
    updatedAt: 'UpdatedAt',
    deletedAt: 'DeletedAt',
    tableName: 'AppDepartments',
    indexes: [
      {
        unique: true,
        fields: ['DepartmentName']
      }
    ]
  });
  Department.associate = function(models) {
    Department.hasMany(models.User, {
      foreignKey: 'DepartmentId'
    });
  };
  return Department;
};
exports.getUsers = async (req, res, next) => {
  const showDeleted = ( req.headers.showdeleted == 'false' ); 
  await User.findAll({
    attributes: ['UserId', 'FirstName', 'LastName', 'Username', 'Email', 'OfficePhone', 'IsActive', 'DeletedAt'],
    include: [
      { model: Department, attributes: ['DepartmentName'] },
      { model: Contractor, attributes: ['ContractorName'] }
    ],
    paranoid: showDeleted,
    order: [
      ['LastName', 'ASC']
    ]
  })
    .then(results => {
      res.status(200).send(results);
    })
    .catch(err => {
      console.log(err);
    })
};
生成的查询

SELECT [User].[UserId], 
[User].[FirstName], 
[User].[LastName], 
[User].[Username], 
[User].[Email], 
[User].[OfficePhone], 
[User].[IsActive], 
[User].[DeletedAt], 
[Department].[DepartmentId] AS [Department.DepartmentId], 
[Department].[DepartmentName] AS [Department.DepartmentName], 
[Contractor].[ContractorId] AS [Contractor.ContractorId], 
[Contractor].[ContractorName] AS [Contractor.ContractorName] 
FROM [DrxAppUsers] AS [User] 

LEFT OUTER JOIN [DrxAppDepartments] AS [Department] ON [User].[DepartmentDepartmentId] = [Department].[DepartmentId] AND ([Department].[DeletedAt] IS NULL) 

LEFT OUTER JOIN [DrxAppContractors] AS [Contractor] ON [User].[ContractorContractorId] = [Contractor].[ContractorId] AND ([Contractor].[DeletedAt] IS NULL) WHERE ([User].[DeletedAt] IS NULL) ORDER BY [User].[LastName] ASC;

正如您在上面所看到的,它正试图加入到“User.DepartmentDepartmentId”(以及User.ContractorContractorId,因为ContractorId也是一个外键)。它为什么这样做?我该如何修复它?我尝试了许多不同的选项,但没有外键,似乎无法找到答案。

在创建关联时,您需要指定外键的命名。如果未指定,则默认为目标的名称+目标的主键。因此,对于您来说,这就是
DepartmentDepartmentId
,您需要
DepartmentId

User.belongsTo(models.Department, {
  targetKey: 'DepartmentId',
  foreignKey: 'DepartmentId' // the key in your source table
});

为什么在deletedAt之后添加tableName:“AppDepartments”?有必要吗?@mike请看下面解决您问题的答案problem@VyasArpit-我被迫使用表命名约定。tableName在对象中的位置并不重要。为了我自己的阅读目的,这正是我所说的。是的,这很有帮助。非常感谢。我还将“as”添加到关联中,这使得关联模型和查询变得更加方便。非常感谢。