TMA
TMA

Reputation: 1499

Sequelize: <table> is not associated to <Table>

I'm getting images is not associated to product! error while binding the association of the model.

ProductImages is associated to Product and ProductImages is associated to Images model. So, i need to render images property into products collection by assigning to it.

The model that i'm trying to bind is as below.

products.model.ts

const Product = SQLize.define('product', {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }
    product_title: { type: new DataTypes.STRING(255) },
    vendor_id: { type: DataTypes.INTEGER }
}); 
Product.hasMany(ProductImages, {foreignKey: 'product_id', targetKey: 'id', as :'product_img_refs'})
export { Product };

product-images.model.ts

const ProductImages = SQLize.define('product_images', {
  id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, },
  product_id: { type: DataTypes.INTEGER },
  product_image_id: { type: DataTypes.INTEGER }
  img_type_id: { type: DataTypes.INTEGER }
});
ProductImages.belongsTo(ImagesModel, {foreignKey: 'product_image_id', targetKey: 'id', as:'product_images' })
export {ProductImages}

images.model.ts:

const ImagesModel = SQLize.define('images', {
  id: { type: DataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true, },
  img_url: { type: DataTypes.STRING }
});
export { ImagesModel }

Below is the repository file on which i have performed the SQLize operation.

public async getProductData() {
  var prodData = Product.findAll({
    include: [
      { model: Vendor, as: 'vendor' }, 
      { model: ProductImages, as: 'product_img_refs' }
      { model: ImagesModel, as: 'product_images' }
    ]
  });
  return prodData;
}

=> Sample product_images table records.

=> Sample images table records.

=> DB Schema for more visualisation.

=> I have checked this answer but it is not relevant to my model as i have three models with different association.

Upvotes: 1

Views: 1908

Answers (1)

RickN
RickN

Reputation: 13500

Instead of both a hasMany and a belongsTo relationship, create a many-to-many relationship on Product to Images and also one from Images to Product.

You can extend the auto-generated table (with ProductId and ImageId columns) by passing the name of a model.

const ProductImages = SQLize.define('ProductImages', {
  // ...
});
Product.belongsToMany(ImagesModel, { through: ProductImages });
ImagesModel.belongsToMany(Product, { through: ProductImages });

You can now do:

await Product.getImages();
await Images.getProducts();

Or use the include option while querying. There are examples in the documentation here. It'll be something like:

await Product.findAll({
  include: ImagesModel,
});
// It will be nested as such:
// { 
//   fields from product
//   Images: {
//     fields from image
//     ProductImages: {
//       fields from the 'through' table
//     }
//   }
// }

Upvotes: 2

Related Questions