[英]Chaining queries with sequelize
在续集中,我想做一些类似的链接findAll函数调用。
我想在像这样的模型上进行一次findAll
const newYorkers = await People.findAll({ where: { city: 'New York' } });
然后使用newYorkers
作为函数的参数,从而在该函数上进行另一个findAll
const get5ThAvenueInhabitants = (citiesInhabitants) => {
return await citiesInhabitants.findAll({ where: { street: '5th Avenue' } });
};
get5ThAvenueInhabitants(newYorkers);
那将行不通,因为在第一个findAll之后,结果不再是模型,而是一系列结果。
是否可以通过续集来实现?
如果你想要做的是的findAll People
谁住在New York
和5th Avenue
,你为什么不使用and
操作?
就这么简单
const newYorkers = People.findAll({
where: {
city: 'New York',
street: '5th Avenue',
},
],
},
});
首先,除了您要询问的内容外,我不了解get5ThAvenueInhabitants()
函数背后的逻辑。 作为上一个答案,您可以使用以下where: { city: 'New York', street: '5th Avenue'}
直接过滤where: { city: 'New York', street: '5th Avenue'}
。 无需先查询“纽约”,再查询“第五大道”。
现在回到您真正要问的问题,关于链接请求,您可以像这样使用async / await:
const mainFunction = async () => {
const newYorkers = await People.findAll({ where: { city: 'New York' } });
get5ThAvenueInhabitants(newYorkers);
}
这样, newYorkers
将等待直到所有数据都被提取,然后继续进行get5ThAvenueInhabitants()
。
如您所述, People.findAll({ where: { city: 'New York' } });
返回instances
数组,而不是model
数组。 instance
对象确实公开了诸如destroy
, update
等之类的方法,因此,从某种意义上讲,您可以通过在返回的实例上使用这些方法来执行某种查询“链接”,如下所示:
People.findAll({ where: { city: 'New York' } }).then(people => {
people.forEach(person => {
person.destroy();
})
});
要在应用程序代码中过滤返回的集合,而不是使用数据库查询,可以执行以下操作:
People.findAll({ where: { city: 'New York' } }).then(people => {
people.filter(person => {
if(person.street === '5th Avenue'){
return person;
}
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.