javascript - 如何直接在Sequelize中更改预加载的结果

标签 javascript node.js sequelize.js

我有两个表,例如 Class 和 Student。

Class.hasMany(Student)
Student.belongsTo(Class)

以下是查询:

async function test(id) {
    await Student.findAll({
        include: [
            {
                model: Class,
                required: true,
                where: {
                    id: id
                }
            }
        ]
    })
        .then(value => console.log(value))
}

输出如下:

[
    {
        "id": 1,
        "name": "ppp",
        "age": 13,
        "Class": {
            "id": 1,
            "monitor": "aaa"
        }
    }
]

我希望它可以是这样的:

[
    {
        "id": 1,
        "name": "ppp",
        "age": 13,
        "class_id": 1,
        "class_monitor": "aaa"
    }
]

我知道我可以通过更改 .then() 中的代码来做到这一点

但是我可以在这部分做一些改变吗:

await Student.findAll({
        include: [
            {
                model: Class,
                required: true,
                where: {
                    id: id
                }
            }
        ]
    })

最佳答案

您可以使用raw:true:

Student.findAll({
    include: [
        {
            model: Class,
            required: true,
            where: {
                id: id
            }
        }
    ],
    raw : true,
});

但这会产生 . 的结果,而不是 _ ,

[
    {
        "id": 1,
        "name": "ppp",
        "age": 13,
        "class.id": 1,
        "class.monitor": "aaa"
    }
]

1) Another way is to create alias with attribute name ,

OR

2) receive the data then you can modifyonce you

关于javascript - 如何直接在Sequelize中更改预加载的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57513329/

相关文章:

javascript - 如何在 findAll 上的 node.js Sequelize 中具有多个关联/条件/包含

javascript - 替换屏幕文本

javascript - 只允许字符或空格的正则表达式

javascript - javascript .split (' ' ) 会将逗号留在数组中吗?

javascript - 如何使用 jquery/javascript 在 safari 中复制到剪贴板?

node.js - S3 设置 Access-Control-Allow-Origin header

node.js - SSL/https 从 header 中删除 X-CSRFToken

angularjs - 仅在单击 SideMenu 后才会显示 Ionic 内容

node.js - SequelizeJS - 使用原始查询将 JSONB 插入到 Postgres - 如何转义

javascript - Node.js Express 与 PostgresQL,sequelize 出错