【问题标题】:Express js + Sequelize queryingExpress js + Sequelize 查询
【发布时间】:2018-02-28 17:59:04
【问题描述】:

我在我的项目中使用 MySQL 数据库。问题考虑复杂查询,其中 Sequelize 未正确检测关系。

我有 4 张桌子:

Post_code | Building | Flat | Invoice

它们是一对多的关系,如下图所示:

这是我要执行的 SQL 查询:

SELECT 
   CONCAT(building.name, ' ', flat.number) as 'buildingInfo',
   CONCAT(building.address,' ',post_code.city,' ',post_code.code) as 
   'address',
   IFNULL(invoice.date,'Unknonw') as 'lastInvoiceDate'
FROM building
INNER JOIN post_code ON post_code.id = building.post_code_id
INNER JOIN flat ON building.id = flat.building_id
LEFT JOIN invoice ON flat.id = invoice.flat_id;

Sequelize 查询:

models.building.findAll({

    attributes: 
    [
       [Sequelize.fn("CONCAT", Sequelize.col("building.name"),' 
       ',Sequelize.col("flats.number")),'buildingInfo'],
       [Sequelize.fn("CONCAT",Sequelize.col("building.address"),' 
       ',Sequelize.col("post_code.city"),' 
       ',Sequelize.col("post_code.code")),'address'],          
       [Sequelize.fn("IFNULL",Sequelize.col("invoice.date"),'Unknown'),
       'lastInvoiceDate']
    ],

    include:
        [
            {
                model: models.flat,
                required: true
            },
            {
                model: models.post_code,
                required: true
            },
            {
                model: models.invoice,
                required: false
            }
        ]

}).then(function (data){
    // Something here
});

问题考虑:“LEFT JOIN invoice ON flat.id = invoice.flat_id;”

我收到“发票”与“建筑”无关的错误。

这是真的,因为这个关系没有在建筑模型中定义,它只与 post_code 和 flat 有联系,但是当我做 JOIN 时,我也可以包含发票表,“通过”平面表。

如何使用 Sequelize 包含此表?

【问题讨论】:

  • 您在公寓内制作了第二个包含,以便您可以使用发票加入
  • 它正在工作,您应该添加您的解决方案作为答案

标签: mysql express join model sequelize.js


【解决方案1】:

您的invoice 模型应包含在flat 模型中,如下所示。

{
    model: models.flat,
    required: true,
    include : [{
        model: models.invoice
        required : false
    }]
}

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 2015-07-31
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    相关资源
    最近更新 更多