从关联的续集中返回平面对象 [英] Return flat object from sequelize with association
问题描述
我正在按顺序转换我的所有查询. 我所遇到的问题是,当选择查询包括关联(例如:一对多),我得到的目的是嵌套的对象的阵列.
I am working on converting all my queries in sequelize. The problem I have come across is that when select queries include associations (ex. one to many), the object I get is an array of nested objects.
它看起来像:
[
{
"field1": "someval",
"field2": "someval1",
"assoc_table": {
"field_a": 1,
"field_b": "someval"
}
},
{
"field1": "someval",
"field2": "someval3",
"assoc_table": {
"field_a": 5,
"field_b": "someval"
}
},
{
"field1": "someval",
"field2": "someval3",
"assoc_table": {
"field_a": 12,
"field_b": "someval"
}
}
]
我尝试使用不同的模块来展平对象(在循环中,每个对象单独),但是我总是遇到一个错误,告诉我我试图展平的不仅仅是对象.
I tried to use different modules to flatten the objects (inside a loop, each object individually), but I always got an error telling that what I was trying to flatten were not just objects.
此外,我宁愿避免将对象弄平的部分,而仅通过续集获得平坦的结果.
Moreover, I would prefer avoiding the part where objects are flattened, and simply get a flat result with sequelize.
续集代码如下所示:
models.table1.findAll({
attributes: ['field1', 'field2'],
where: {field1: someval},
include: [{model: models.assoc_table, required: true, attributes:['field_a', 'field_b']}]
}).then(function (result) {
res.send(result);
}).catch(function(error) {
console.log(error);
});
推荐答案
问题的一部分可能是您的result
是一个模型实例数组,因此如果您不调用toJSON
在数组中的元素上.我提供的代码可以使您的示例变平:
Part of your issue is probably that your result
is an array of model instances, so you might be having issues flattening it if you didn't call toJSON
on the elements in the array. I provided code that would flatten your example:
result.forEach(obj => {
Object.keys(obj.toJSON()).forEach(k => {
if (typeof obj[k] === 'object') {
Object.keys(obj[k]).forEach(j => obj[j] = obj[k][j]);
}
});
});
您还可以将raw: true
作为选项添加到findAll
中,这将使对象变平,但是它看起来像这样:
You can also add raw: true
as an option to findAll
, which will flatten your object, but it will look like this:
[
{
"field1": "someval",
"field2": "someval1",
"assoc_table.field_a": 1,
"assoc_table.field_b": "someval"
},
...
]
这篇关于从关联的续集中返回平面对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!