[英]Sequelize options.nest in query() method doesn't work
I have a raw query like我有一个原始查询,如
squelize.query(
`select "order".id, "orderCustomer".id as "orderCustomer.id", "orderCustomer".forename as "orderCustomer.forename"
from orders as "order"
join customers as "orderCustomer" on "orderCustomer".id = "order"."orderCustomerId"
where "orderCustomer".forename ilike '%petra%';`,
{
type: Sequelize.QueryTypes.SELECT,
model: order,
nest: true,
mapToModel: true
})
When I query this in psql
I get a correct result set:当我在
psql
查询时,我得到一个正确的结果集:
-[ RECORD 1 ]----------+------
id | 383
orderCustomer.id | 446
orderCustomer.forename | Petra
-[ RECORD 2 ]----------+------
id | 419
orderCustomer.id | 9
orderCustomer.forename | Petra
The problem is, that Sequelize is apparently not able to form this into an Array of the kind问题是,Sequelize 显然无法将其形成这样的数组
[
{
id: 383,
orderCustomer: {
id: 446,
forename: 'Petra'
}
},
...
]
Instead I get something like this:相反,我得到了这样的东西:
[
{
id: 383,
'orderCustomer.id': 446,
'orderCustomer.forename': 'Petra'
},
...
]
Do I need to include
the customer-model in the query's option-object?我是否需要在查询的选项对象中
include
客户模型?
I logged the result of my query.我记录了我的查询结果。 There is this property
_options
on all of the returned order-instances:在所有返回的订单实例上都有这个属性
_options
:
_options:{
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true, // <--------- possible cause?
attributes: undefined
}
Somehow, I cannot set options.raw
to false
on my query definition!不知何故,我无法在我的查询定义中将
options.raw
设置为false
! Maybe that is the reason why …也许这就是为什么……
…sequelize will not try to format the results of the query, or build an instance of a model from the result (see docs > query() > options.raw )
...sequelize 不会尝试格式化查询结果,也不会根据结果构建模型实例(请参阅docs > query() > options.raw )
Any ideas?有任何想法吗?
我正在使用您的解决方案:nest: true 并且效果很好!
[err, rows] = await to(sequelize.query(query,{ replacements: { search: '%'+search+'%', limit: limit, offset: skip}, type: sequelize.QueryTypes.SELECT,nest: true}));
Try it without the不带就试试
model: order,
this solved it for me这为我解决了
Assuming you have the models set up properly,假设您已正确设置模型,
Why not query it using associations, instead of using a raw query.为什么不使用关联来查询它,而不是使用原始查询。 Something like this should generate a similar result
这样的事情应该产生类似的结果
Model.Order.findAll({
where:{forename:{$iLike:'someString'}},
attributes:[/*Columns to fetch*/]
include:[{model:Model.Customer,attributes:[/*Columns to fetch*/]}]
});
Also IMO using the nest attributes, wont club across multiple rows returned.此外,IMO 使用嵌套属性,不会跨多行返回。
I had the same issue and made it work this way:我遇到了同样的问题,并使其以这种方式工作:
sequelize.query(
`SELECT q.id, q.title, a.id AS "answers.id"
FROM questions q
JOIN answers a ON a.question_id = q.id`,
model: Question,
mapToModel: true,
nest: true,
raw: true,
type: sequelize.QueryTypes.SELECT }
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.