Referencing a composite primary key in a Sequelize.js seed model
model/product.js:
const Product = sequelize.define("product", {
sku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
title: { type: Sequelize.STRING, allowNull: false },
availability: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: false,
}
});
model/Attribute.js:
const Attribute = sequelize.define("attribute", {
key: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
productSku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
value: { type: Sequelize.STRING, allowNull: false },
});
After importing to app.js:
product.hasMany(attribute, { foreignKey: "productSku", sourceKey: "sku" });
attribute.belongsTo(product, { foreignKey: "productSku", targetKey: "sku" });
Explanation:
Product.sku is exported as foreign key to Attibute.productSku. Attribute table has a composite foreign (key + productSku), and a ForeignKey(productSku) from product.sku;
While it is possible to create composite primary keys in Sequelize by specifying primaryKey: true
against more than one column (as you have already done above), Sequelize doesn't currently support composite foreign keys, so there is no way to reference a model/table which has composite primary keys.
See https://github.com/sequelize/sequelize/issues/311 for a discussion on the subject.