问题描述
有时我只想从多行中选择一个值.
Sometimes i only want to select a single value from multiple rows.
假设我有一个如下所示的帐户模型:
Lets imagine i have an account model which looks like this:
帐户
- 身份证
- 姓名
- 年龄
我只想选择名字.
你会这样写:
AccountModel.findAll({
where: {
Age: {
$gt : 18
}
},
attributes: ['Name'],
raw : true
});
但这会返回一个带有对象的数组.
But this would return in an array with objects.
[{Name : "Sample 1"}, {"Name" : "Sample 2"}]
我想得到一个只有这样名字的数组:
I would like to get an array with only names like this:
["Sample 1", "Sample 2"]
是否可以通过 Sequelize 实现这一目标?我已经搜索了文档但找不到它.
Is it possible to achieve this with Sequelize? I've searched trough the documentation but couldn't find it.
推荐答案
使用 Sequelize 3.13.0 似乎不可能让 find
返回一个平面数组而不是数组对象.
Using Sequelize 3.13.0 it looks like it isn't possible to have find
return a flat array of values rather than an array of objects.
解决问题的一种方法是使用下划线或 lodash 映射结果:
One solution to your problem is to map the results using underscore or lodash:
AccountModel.findAll({
where: {
Age: {
$gt : 18
}
},
attributes: ['Name'],
raw : true
})
.then(function(accounts) {
return _.map(accounts, function(account) { return account.Name; })
})
我已经上传了一个脚本来演示这个 这里.
I've uploaded a script that demonstrates this here.
作为快速说明,设置 raw: true
会使 Sequelize 查找方法返回普通的旧 JavaScript 对象(即没有实例方法或元数据).这可能对性能很重要,但不会更改转换为 JSON 后的返回值.这是因为 Instance::toJSON 总是返回一个普通的JavaScript 对象(无实例方法或元数据).
As a quick note, setting raw: true
makes the Sequelize find methods return plain old JavaScript objects (i.e. no Instance methods or metadata). This may be important for performance, but does not change the returned values after conversion to JSON. That is because Instance::toJSON always returns a plain JavaScript object (no Instance methods or metadata).
这篇关于用字符串而不是对象对返回数组进行续集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!