我使用自动生成的函数“ addXXXs”收到错误的查询
型号:
module.exports = (sequelize, types) => {
return sequelize.define('Product', {
internal_code:{type:types.STRING},
name:{type:types.STRING},
description:{type:types.STRING},
unit:{type:types.STRING},
precio:{type:types.DECIMAL},
alicuota:{type:types.DECIMAL},
stock:{type:types.INTEGER},
service:{type:types.INTEGER}
})
}
module.exports = (sequelize, types) => {
return sequelize.define('Imageproduct', {
image:{type:types.STRING}
})
}
关系:
db.Imageproduct.belongsTo(db.Product);
db.Product.hasMany(db.Imageproduct);
查询:
product = await db.Product.create(my_product);
images = await db.Imageproduct.bulkCreate(my_images_list);
assoc = await product.addImageproducts(images);
生成的查询:
1 - Executing (default): INSERT INTO "Products" ("internal_code","name","description","unit","precio","alicuota","stock","service","createdAt","updatedAt") VALUES ('P007','
Guitarra electrica','Guitarra electrica','',32.1,0.21,5,0,'2019-04-01 21:30:17.498 +00:00','2019-04-01 21:30:17.498 +00:00') RETURNING *;
2 - Executing (default): INSERT INTO "Imageproducts" ("id","image","createdAt","updatedAt") VALUES (DEFAULT,'blabla.png','2019-04-01 21:30:17.591 +00:00','2019-04-01 21:30:
17.591 +00:00'),(DEFAULT,'blabla.jpg','2019-04-01 21:30:17.591 +00:00','2019-04-01 21:30:17.591 +00:00');
3 - Executing (default): UPDATE "Imageproducts" SET "ProductId"=3,"updatedAt"='2019-04-01 21:30:17.667 +00:00' WHERE "id" IN (NULL, NULL)
1和2是正确的,但是我希望在查询3的IN子句中有一些有效的ID,而不是NULL,实际上,我希望在查询3的IN子句中插入图像的ID。 有人知道为什么会这样吗?
谢谢。
答案 0 :(得分:0)
替换
images = await db.Imageproduct.bulkCreate(my_images_list);
到
images = await db.Imageproduct.bulkCreate(my_images_list, { returning:true });
这样,您可以在图像对象中获取新记录的ID。 (仅限于PostgreSQL)