js查询通过关系获得总数

Sequelize.js query to get total count through relationship

本文关键字:关系 查询 js      更新时间:2023-09-26

我使用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

这很好。但不确定如何获得序列化查询。

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:

因为经常有这样的用例,它只是更容易执行原始/已经准备好的SQL查询,可以利用该函数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

假设您已经定义了关联,您可以使用Model.findAndCountAll。它看起来像这样:

Parcel.findAndCountAll({
  include: [{
    model: OrderParcel,
    required: true,
    include: [{
      model: Order,
      where: {
        customerId: idNum
      }
    }]
  }]
}).then(function(result) { 
});

我完全同意Evan Siroky的方法,但是代码必须简化才能正常工作:

Parcel.findAndCountAll({
include: [{
  model: Order,
  where: {
    customerId: idNum
  },
  duplicating: false // Add this line for retrieving all objects
}]
}).then(function(result) { 
   console.log('Rows: ' + result.rows + ' Count: ' + result.count)
});

记得用belongsToMany方法连接你的模型!