链接查询



在semelize中,我想做一些诸如链接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之后,结果不再是模型,而是结果。

可以通过续集实现此目标?

如果您要做的就是找到居住在New York5th Avenue中的People,为什么不使用and操作员?

它将像

一样简单

const newYorkers = People.findAll({ 
  where: { 
       city: 'New York',
       street: '5th Avenue',
      },
    ],
  },
});

首先,除了您的要求之外,我不了解函数get5ThAvenueInhabitants()背后的逻辑。作为上一个答案,您可以使用where: { city: 'New York', street: '5th Avenue'}直接过滤。无需首先查询"纽约",然后是"第五大道"。

现在回到您真正要求的内容,链接请求您可以使用异步/等待这样的请求:

const mainFunction = async () => {
    const newYorkers = await People.findAll({ where: { city: 'New York' } });
    get5ThAvenueInhabitants(newYorkers);
}

以这种方式,newYorkers将等待所有数据都获取,然后继续进行get5ThAvenueInhabitants()

如您所提到的,People.findAll({ where: { city: 'New York' } });返回instances的数组,而不是modelinstance对象确实会揭示destroyupdate等的方法,因此,从某种意义上说,您可以通过在返回的实例上使用这些方法来进行某种查询"链接",例如:

People.findAll({ where: { city: 'New York' } }).then(people => {
     people.forEach(person => {
         person.destroy();
     })
 });

要过滤您的应用程序代码中的返回集合,而不是使用DB查询,您可以做类似的事情:

 People.findAll({ where: { city: 'New York' } }).then(people => {
     people.filter(person => {
        if(person.street === '5th Avenue'){
            return person;
        }
     })
 });

最新更新