使用 Sequelize (NodeJS) 而不是 * 指定特定字段
好的,所以我在 NodeJS 中有一个项目,我将 Sequelize 用于 MySQL ORM.这件事非常有效,但是我试图弄清楚是否有一种方法可以指定基于查询返回哪些字段,或者是否有一种方法可以在某处执行 .query() .
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.
例如,在我们的用户数据库中,记录和列的数量可能非常多.在这种情况下,我只需要返回三列,因此只获取这些列会更快.但是,Sequelize 只是在表中查询所有*"以尽可能地满足完整的对象模型.这是我想在应用程序的这个特定区域绕过的功能.
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.
推荐答案
您必须将属性指定为传递给 findAll() 的对象中的属性:
You have to specify the attributes as a property in the object that you pass to findAll():
Project.findAll({attributes: ['name', 'age']}).on('success', function (projects) {
console.log(projects);
});
我是如何发现这个的:
这里首先调用查询: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
相关文章