使用 Sequelize (NodeJS) 代替 * 指定特定字段
好吧,我在 NodeJS 中有一个项目,我正在其中使用 Sequelize 来实现 MySQL ORM。这件事工作得非常好,但是我试图弄清楚是否有一种方法可以指定在查询的基础上返回哪些字段,或者是否有一种方法可以在某处执行 .query() 。
例如,在我们的用户数据库中,可能存在大量的记录和列。在本例中,我只需要返回三列,因此仅获取这些列会更快。然而,Sequelize 只是在表中查询所有“*”,以尽可能满足完整的对象模型。这是我想在应用程序的这个特定区域中绕过的功能。
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须将属性指定为传递给 findAll() 的对象中的属性:
我是如何发现这一点的:
首先在此处调用查询: 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
You have to specify the attributes as a property in the object that you pass to findAll():
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
在新版本中尝试一下
Try this in new version
所有答案都是正确的,但我们也可以使用
include
和exclude
以及来源
All Answers are correct but we can also use
include
andexclude
as wellSource
在属性键中使用数组。您可以为别名执行嵌套数组。
将产生:
Use the arrays in the attribute key. You can do nested arrays for aliases.
Will yield: