Sequelize.Js-PostgreSQL如何从属于表的关联表中获取行?

时间:2017-11-26 12:43:18

标签: node.js postgresql sequelize.js has-many

我正在尝试检索ReceiptItems中的相关行,来自收据的付款相互连接的hasMany和belongsTo方法。

这是我的表关系:

// One to Many Relationship between receiptitems and receipts
db.Receipts.hasMany(db.ReceiptItems,{ foreignKey : 'receipt_id'});
db.ReceiptItems.belongsTo(db.Receipts,{ foreignKey : 'receipt_id'});

// One to Many Relationship between ReceiptItems and Payments
// This relation exists due to solve the problem of paying the debts later on !
db.Receipts.hasMany(db.Payments, { foreignKey : 'receipt_id' });
db.Payments.belongsTo(db.Receipts, { foreignKey : 'receipt_id' });

// One to many Relationship between Receipts and Plates
db.Plates.hasMany(db.Receipts, { foreignKey : 'plate_id' });
db.Receipts.belongsTo(db.Plates, { foreignKey : 'plate_id' });

这里我的方法是找到属于plate_id的收据,它找到收据但是它没有检索与收据相关的ReceiptItems和Payments(非空变量,我看不到任何与相关表格相关的字段。成功复出。)

db.Receipts.findAll({
        where : {
          plate_id : result.plate_id
        }
      },{
        include : [ { associaton : db.ReceiptItems}, { association : db.Payments} ]
      }).then((receiptResult)=>{
        console.log(receiptResult);
      }).catch((receiptErr)=>{
        console.log(receiptErr);
      })

1 个答案:

答案 0 :(得分:0)

我刚刚发现了遇到问题的原因。

首先,在where语句之后,我有一个额外的结束块括号,我必须以下面的方式使用关联:

db.Receipts.find({
        where : {
          plate_id : result.plate_id
        },
        include : [{ association : db.Receipts.associations.ReceiptItems},{ association : db.Receipts.associations.Payments }]
      }).then((receiptResult)=>{
        console.log(receiptResult);
      }).catch((receiptErr)=>{
        console.log(receiptErr);
      })