【发布时间】:2020-06-17 21:14:14
【问题描述】:
我在绑定模型的关联时收到images is not associated to product! 错误。
ProductImages 与 Product 关联,ProductImages 与 Images 模型关联。所以,我需要将images 属性分配给products 集合。
我尝试绑定的模型如下。
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 }
下面是我执行 SQLize 操作的存储库文件。
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;
}
=> 示例product_images 表记录。
=> 示例 images 表记录。
=> DB Schema 以获得更多可视化。
=> 我已经检查了这个answer,但它与我的模型无关,因为我有三个具有不同关联的模型。
【问题讨论】:
标签: node.js sequelize.js