MySQL 使用 Sequelize (NodeJS) 而不是 * 指定特定字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8039932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:34:56  来源:igfitidea点击:

Specifying specific fields with Sequelize (NodeJS) instead of *

mysqlnode.jssequelize.js

提问by Aric

Alright so I have a project in NodeJS where I'm utilizing Sequelize for a MySQL ORM. The thing works fantastically however I'm trying to figure out if there is a way to specify what fields are being returned on a query basis or if there's even a way just to do a .query() somewhere.

好的,所以我在 NodeJS 中有一个项目,我将 Sequelize 用于 MySQL ORM。这件事非常有效,但是我试图弄清楚是否有一种方法可以指定在查询基础上返回哪些字段,或者是否有一种方法可以在某处执行 .query() 。

For example in our user database there can be ridiculous amounts of records and columns. In this case I need to return three columns only so it would be faster to get just those columns. However, Sequelize just queries the table for everything "*" to fulfill the full object model as much as possible. This is the functionality I'd like to bypass in this particular area of the application.

例如,在我们的用户数据库中,可能有大量的记录和列。在这种情况下,我只需要返回三列,这样就可以更快地获得这些列。然而,Sequelize 只是查询表中所有“*”的内容,以尽可能满足完整的对象模型。这是我想在应用程序的这个特定区域中绕过的功能。

回答by alessioalex

You have to specify the attributes as a property in the object that you pass to findAll():

您必须将属性指定为传递给 findAll() 的对象中的属性:

Project.findAll({attributes: ['name', 'age']}).on('success', function (projects) {
  console.log(projects);
});

How I found this:

我是如何找到这个的:

The query is first called here: https://github.com/sdepold/sequelize/blob/master/lib/model-definition.js#L131
Then gets constructed here: https://github.com/sdepold/sequelize/blob/master/lib/connectors/mysql/query-generator.js#L56-59

查询首先在此处调用:https: //github.com/sdepold/sequelize/blob/master/lib/model-definition.js#L131
然后在此处构造:https: //github.com/sdepold/sequelize/blob /master/lib/connectors/mysql/query-generator.js#L56-59

回答by Adiii

Try this in newversion

版本中试试这个

template.findAll({
    where: {
        user_id: req.params.user_id //array
    },
    attributes: ['id', 'template_name'], //object
}).then(function (list) {
    res.status(200).json(list);
})

回答by GavinBelson

Use the arrays in the attribute key. You can do nested arrays for aliases.

使用属性键中的数组。您可以为别名执行嵌套数组。

Project.findAll({
  attributes: ['id', ['name', 'project_name']],
  where: {id: req.params.id}
})
.then(function(projects) {
  res.json(projects);
})

Will yield:

将产生:

SELECT id, name AS project_name FROM projects WHERE id = ...;