【问题标题】:How to return result from include model in same level of main model in Sequelize?如何从 Sequelize 中与主模型相同级别的包含模型返回结果?
【发布时间】:2020-10-11 21:01:48
【问题描述】:

这是我在项目中完成的代码和结果。 我想在与主模型相同的结果中获得包含模型的结果。下面的代码是我所做的。

Sequelize 查询:

 User.findAll({
        include: [{
                model: Position,
                attributes: ['POSITION_NAME'],
            }
        ]
    }).then(user => {
        res.json({
            data: user
        })
    }).catch(error => {
        console.log(error)
    })

我得到的结果

     [
        {
            "ID": 2,
            "NAME": "AAA",
            "LAST_NAME": "BBB",
            "Position": {
                "POSITION_NAME": "ວິຊາການສັນຍາຈ້າງ"
            }
        }
]

我想要的结果:

     [
        {
            
        "ID": 2,
        "NAME": "AAA",
        "LAST_NAME": "BBB",
        "POSITION_NAME": "ວິຊາການສັນຍາຈ້າງ"
        }
]

【问题讨论】:

    标签: mysql express sequelize.js


    【解决方案1】:

    像这样试试。

    User.findAll({
        attributes: ["ID", "NAME", ["Position.POSITION_NAME", "POSITION_NAME"]],
        include: [{
            model: Position,
            attributes: [],
        }
        ],
        raw:true
    }).then(user => {
        res.json({
            data: user
        })
    }).catch(error => {
        console.log(error)
    })
    

    【讨论】:

    • 谢谢,但发生了错误。原文:错误:“字段列表”中的未知列“Position.POSITION_NAME”
    • 我已经更新了我的代码试试看。如果它仍然不起作用,请分享您的架构。
    • 哇,在我设置 raw: true 之后。输出是我想要的:)。非常感谢@Vyas Arpit
    • 很高兴 :)
    • 运行良好,attributes: ["ID", "NAME", "Position.POSITION_NAME", "POSITION_NAME"],
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 2021-12-28
    相关资源
    最近更新 更多