简体   繁体   English

Sequelize many-to-many:识别较低的camelCase别名,而是尝试使用上层CamelCase?

[英]Sequelize many-to-many: recognise lower camelCase alias and instead try upper CamelCase?

I am not able to query a many-to-many-association with Sequelize, and I speculate that it's related to a lower/uppercase-issue. 我无法查询与Sequelize的多对多关联,我猜测它与低/大写问题有关。

My alias and column name is camelCase ( extraId ), but the generated query seems to try TitleCased ( ExtraId ), but this is inferred from the error message below. 我的别名和列名是camelCaseextraId ),但生成的查询似乎尝试使用TitleCasedExtraId ),但这可以从下面的错误消息中推断出来。


I want to query all Products with their associated list of Extras , and I try to do that as following: 我想查询所有Products及其相关的Extras列表,我尝试按以下方式执行此操作:

    const data = await models.Product.findAll(
      {
        include: [{
          model: models.Extra,
          as: 'extras'
        }]
      }
    );

However, that gives the me the following error: 但是,这给了我以下错误:

column extras->ProductExtras.ExtraId does not exist

I have three tables, Products , Extras , and their association table ProductExtras defined as following: 我有三个表, ProductsExtras ,以及它们的关联表ProductExtras定义如下:

  const Product = sequelize.define('Product', {
    name: {
        allowNull: false,
        type: DataTypes.STRING
    }
  }, {});
  Product.associate = function(models) {
    Product.belongsToMany(models.Extra, {
      as: 'extras',
      through: 'ProductExtras'
    });
  };



  const Extra = sequelize.define('Extra', {
    code: DataTypes.INTEGER,
    desc: DataTypes.STRING
  }, {});
  Extra.associate = function(models) {
    Extra.belongsToMany(models.Product, {
      as: 'products',
      through: 'ProductExtras'
    })
  };



  const ProductExtras = sequelize.define('ProductExtras', {
    productId: DataTypes.INTEGER,
    extraId: DataTypes.INTEGER
  }, {});
  ProductExtras.associate = function(models) {
    ProductExtras.belongsTo(models.Product, {foreignKey: 'productId'});
    ProductExtras.belongsTo(models.Extra, {foreignKey: 'extraId'})
  };

Any insights or solution to this issue would be greatly appreciated. 任何有关此问题的见解或解决方案将不胜感激。

Have you tried adding a foreign key to the belongsToMany, as shown below? 您是否尝试过将外键添加到belongsToMany,如下所示? That's what I use to override the default column name for a join-table. 这就是我用来覆盖连接表的默认列名。

Product.associate = function(models) {
    Product.belongsToMany(models.Extra, 
      {
      as: 'extras',
      through: 'ProductExtras',
      foreignKey : 'extraId'
      }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM