Sequelize:通过联接表的belongsToMany关联

时间:2019-03-04 19:59:23

标签: sequelize.js associations has-and-belongs-to-many

这是我致电product.getAttributeValues()时遇到的错误:

  

未处理的拒绝SequelizeDatabaseError:未知列   “字段列表”中的“ ProductAttribute.attribute_id”

我不知道ProductAttribute.attribute_id来自何处

这是产生以下内容的SQL查询:

  

执行(默认):SELECT AttributeValueattribute_value_id,   AttributeValuevalueAttributeValueattribute_id,   ProductAttributeproduct_idProductAttribute.product_id,   ProductAttributeattribute_idProductAttribute.attribute_id,   ProductAttributeattribute_value_id为   ProductAttribute.attribute_value_id,   ProductAttributeattribubte_value_id为   ProductAttribute.attribubte_value_id来自attribute_value AS   AttributeValue作为product_attribute的内部联接ProductAttribute   开启AttributeValueattribute_value_id =   ProductAttributeattribubte_value_id并且   ProductAttributeproduct_id = 1;

我有这个模式:

enter image description here

这些Sequelize模型关联:

module.exports = (sequelize, DataTypes) => {
  var Product = sequelize.define('Product', {
  product_id: {
    autoIncrement: true,
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,

  },
}, {tableName: 'product', timestamps: false},
);
  Product.associate = function(models) {
    Product.belongsToMany(models.AttributeValue, { through: 'ProductAttribute', foreignKey: 'product_id', otherKey: 'attribubte_value_id'})
    Product.belongsTo(models.Category, { through: 'ProductCategory', foreignKey: 'product_id', otherKey: 'category_id'})
  };
  return Product;
};

module.exports = (sequelize, DataTypes) => {
  var AttributeValue = sequelize.define('AttributeValue', {
  attribute_value_id: {
    autoIncrement: true,
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
  },
  value: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  attribute_id: {
    allowNull: false,
    type: DataTypes.INTEGER,
   references: {
     // This is a reference to another model
     model: models.Attribute,
     // This is the column name of the referenced model
     key: 'attribute_id',
   }
  },
}, {tableName: 'attribute_value', timestamps: false},
);
  AttributeValue.associate = function(models) {
    AttributeValue.hasOne(models.Attribute, {foreignKey: 'attribute_id'})
    AttributeValue.belongsToMany(models.Product, {through: 'ProductAttribute', foreignKey: 'attribute_value_id', otherKey: 'product_id'})

  };
  return AttributeValue;
};
module.exports = (sequelize, DataTypes) => {
  var ProductAttribute = sequelize.define('ProductAttribute', {
  product_id: {
    type: DataTypes.INTEGER,
    primaryKey: true,    
  },
  attribute_id: {
    type: DataTypes.INTEGER,
    primaryKey: true,   
  },
}, {tableName: 'product_attribute', timestamps: false},
);
  ProductAttribute.associate = function(models) {
  };
  return ProductAttribute;
};

如何设置关联,以便product.getAttributeValues()返回某个产品的所有attributeValue,反之亦然

0 个答案:

没有答案