我希望在模型的属性中具有多个计数。我的意思是,我有一个模型:产品,该模型被引用并与模型“库存”和“采购”相关联。
它与股票模型很好地配合。我完全得到了计数数字。所以我希望购买模式也一样。
Product.findOne({
include: [{
model: User,
attributes: ["id", "username", "jabber", "email"],
as: 'creator'
},
{
model: Category,
as: 'category'
},
{
model: ProductImage,
as: 'images'
},
{
model: Stock,
attributes: []
},
{
model: Purchase,
attributes: [],
}],
attributes: {
exclude: ['fk_creator'],
// THIS IS THE PART WHICH NOT WORKS AS EXPECTED
include: [[Sequelize.fn("COUNT", Sequelize.col("stocks.fk_product")), "stock_count"],// this works
[Sequelize.fn("COUNT", Sequelize.col("purchases.fk_product")), "buy_count"]] // this gives just the same as stock_count but should give another number
},
where: {id: id},
group: ['product.id', 'images.id']
}).then((product) => {
res.send({status: true, data: product})
}).catch((err) => {
next(err)
});
这是由sequelize生成的查询:
SELECT `product`.`id`,
`product`.`title`,
`product`.`description`,
`product`.`product_type`,
`product`.`price`,
`product`.`catid`,
`product`.`rating`,
`product`.`createdat`,
`product`.`updatedat`,
Count(`stocks`.`fk_product`) AS `stock_count`,
Count(`purchases`.`fk_product`) AS `buy_count`,
`creator`.`id` AS `creator.id`,
`creator`.`username` AS `creator.username`,
`creator`.`jabber` AS `creator.jabber`,
`creator`.`email` AS `creator.email`,
`category`.`id` AS `category.id`,
`category`.`catname` AS `category.catname`,
`category`.`icon` AS `category.icon`,
`category`.`createdat` AS `category.createdAt`,
`category`.`updatedat` AS `category.updatedAt`,
`images`.`id` AS `images.id`,
`images`.`fk_product` AS `images.fk_product`,
`images`.`imageurl` AS `images.imageurl`,
`images`.`is_first` AS `images.is_first`,
`images`.`createdat` AS `images.createdAt`,
`images`.`updatedat` AS `images.updatedAt`
FROM `products` AS `product`
LEFT OUTER JOIN `users` AS `creator`
ON `product`.`fk_creator` = `creator`.`id`
LEFT OUTER JOIN `categories` AS `category`
ON `product`.`catid` = `category`.`id`
LEFT OUTER JOIN `product_images` AS `images`
ON `product`.`id` = `images`.`fk_product`
LEFT OUTER JOIN `stocks` AS `stocks`
ON `product`.`id` = `stocks`.`fk_product`
LEFT OUTER JOIN `purchases` AS `purchases`
ON `product`.`id` = `purchases`.`fk_product`
WHERE `product`.`id` = '1'
GROUP BY `product`.`id`,
`images`.`id`;
所以我得到一个数字,但它总是与stock_count相同。