【问题标题】:Sequelize.js query to get total count through relationshipSequelize.js 查询通过关系获取总数
【发布时间】:2016-01-06 00:53:52
【问题描述】:

我正在使用 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'
});

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    一种方法是使用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

    【讨论】:

    • 是的,我现在正在使用原始查询,但希望避免这种情况。
    • 好吧,因为关节我没有看到其他方式。
    • @Rob 看到我的回答以避免原始查询
    【解决方案2】:

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

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

    【讨论】:

    • 我收到了Error: OrderParcel is not associated to Parcel,我已将OrderParcel 代码添加到问题中。
    • 确保为 Parcel 和 Order 添加 .hasMany 关联。您甚至可以在此表结构中使用 belongsToMany。 (docs.sequelizejs.com/en/latest/docs/associations/…)
    【解决方案3】:

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

    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 方法连接你的模型!

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多