gpt4 book ai didi

javascript - Sequelize.js 查询通过关系获取总数

转载 作者:搜寻专家 更新时间:2023-11-01 00:06:58 24 4
gpt4 key购买 nike

我正在使用 sequelize 通过关系获取总计数。我需要通过一个 customerId 来获取它,它位于通过数据透视表连接的父表中。普通查询看起来像这样:

SELECT count(p.*) FROM parcels as p
LEFT JOIN orders_parcels as op ON op."parcelId" = p.id
LEFT JOIN orders as o ON op."orderId" = o.id
WHERE o."customerId"=1

这很好用。但不确定如何获取 sequelize 查询。

Parcel.findAndCountAll();

编辑:OrderParcel

var OrderParcel = service.sequelize.define('OrderParcel', {

id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
}
}, {
tableName: 'orders_parcels',
freezeTableName: true,
paranoid: true
});

module.exports = OrderParcel;

var Order = require('./Order');

OrderParcel.belongsTo(Order, {
as: 'Order',
foreignKey: 'orderId'
});

var Parcel = require('../parcel/Parcel');

OrderParcel.belongsTo(Parcel, {
as: 'Parcel',
foreignKey: 'parcelId'
});

最佳答案

一种方法是使用sequelize.query:

As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize the function sequelize.query.

var query = "SELECT count(p.*) FROM parcels as p" +
" LEFT JOIN orders_parcels as op ON op."parcelId" = p.id" +
" LEFT JOIN orders as o ON op."orderId" = o.id" +
" WHERE o.customerId=1;";

sequelize.query(query, { type: sequelize.QueryTypes.SELECT}).success(function(count){
console.log(count); // It's show the result of query
res.end();
}).catch(function(error){
res.send('server-error', {error: error});
});

Raw Queries docs

关于javascript - Sequelize.js 查询通过关系获取总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015142/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com