2016-12-01 15 views
0

我想這樣做:Sequelize:對模型A的一個子集,總結相關聯的模型B的整數屬性

select sum("quantity") as "sum" 
from "orderArticles" 
inner join "orders" 
on "orderArticles"."orderId"="orders"."id" 
and "orderArticles"."discountTagId" = 2 
and "orders"."paid" is not null; 

這導致在我的數據的基礎上:

sum 
----- 
151 

(1 row) 

我該怎麼辦?

我Sequelize解決方案:

的模型定義:

const order = Conn.define('orders', { 
     id: { 
      type: Sequelize.BIGINT, 
      autoIncrement: true, 
      primaryKey: true 
     }, 
     // ... 
     paid: { 
      type: Sequelize.DATE, 
      defaultValue: null 
     }, 
     // ... 
    }, 
// ... 
}) 

const orderArticle = Conn.define('orderArticles', 
    { 
     id: { 
      type: Sequelize.BIGINT, 
      autoIncrement: true, 
      primaryKey: true 
     }, 

     // ... 

     quantity: { 
      type: Sequelize.INTEGER, 
      defaultValue: 1 
     } 
    }, 
    { 
     scopes: { 
      paidOrders: { 
       include: [ 
        { model: order, where: { paid: {$ne: null}} } 
       ] 
      } 
     }, 
// ... 
}) 

協會:

orderArticle.belongsTo(order) 
order.hasMany(orderArticle, {onDelete: 'cascade', hooks: true}) 

我想出了這樣的研究小時後:

db.models.orderArticles 
.scope('paidOrders') // select only orders with paid: {$ne: null} 
.sum('quantity', { // sum up all resulting quantities 
    attributes: ['quantity'], // select only the orderArticles.quantity col 
    where: {discountTagId: 2}, // where orderArticles.discountTagId = 2 
    group: ['"order"."id"', '"orderArticles"."quantity"'] // don't know why, but Sequelize told me to 
}) 
.then(sum => sum) // return the sum 

導致這個SQL:

SELECT 「orderArticles」 「量」,SUM( 「量」)作爲 「總和」, 「訂單」, 「ID」 AS 「order.id」,「訂單。 」。 「TAXRATE」 AS 「order.taxRate」, 「秩序」。 「shippingCosts」 AS 「order.shippingCosts」, 「訂單」, 「打折」 AS 「order.discount」, 「訂單」, 「有償」 AS 「order.paid」, 「秩序」。 「出動」 AS 「order.dispatched」, 「訂單」, 「發薪日」 AS 「order.payday」, 「秩序」。 「billNr」 AS 「order.billNr」 「秩序」。 「createdAt」 AS 「order.createdAt」, 「秩序」。 「updatedAt」 AS 「order.updatedAt」, 「秩序」。 「orderCustomerId」 AS 「order.orderCust omerId 「 」命令「, 」billCustomerId「 AS 」order.billCustomerId「 FROM 」orderArticles「 AS 」orderArticles「 INNER JOIN 」訂單「 AS 」順序「 ON 」orderArticles「。 」訂單ID「= 」命令「。」 ID 「 AND」order「。」paid「IS NOT NULL WHERE」orderArticles「。」discountTagId「= '4'GROUP BY」order「。」id「,」orderArticles「。」quantity「;

具有相同的數據的基礎這樣的結果:0 rows

如果你知道我得到了什麼錯了,請讓我知道! 謝謝:)

回答

0

找到了解決辦法:

scopes: { 
    paidOrders: { 
     include: [{ 
      model: order, 
      where: { paid: {$ne: null}}, 
      attributes: [] // don't select additional colums! 
     }] 
    } 
}, 
//... 

和算法:

db.models.orderArticles 
    .scope('paidOrders') 
    .sum('quantity', { 
     attributes: [], // don't select any further cols 
     where: {discountTagId: 2} 
    }) 

注:

在上orderArticle模型的範圍定義

在我的情況足以回報這個承諾。我使用GraphQL來解析結果並將其發送給客戶端。

相關問題