简体   繁体   English

如何查询具有不同属性的模型

[英]How to query a model with different attributes

I'm building an app in Express and using Postgres for my database, Sequelize for ORM. 我正在Express中构建应用程序,并将Postgres用于数据库Sequelize for ORM。

In my database each Post can have one of the 5 types, 1 , 2 , 3 , 4 , 5 . 在我的数据库中的每个Post可以具有5种类型之一, 12345

I want to show the amount of all the posts by type. 我想按类型显示所有帖子的数量。

router.route('/post).get(async (req, res) => {
  const postOne = await Post.findAll({
    where: { 
      state: 1
    }
  });
  const postTwo = await Post.findAll({
    where: { 
      state: 2
    }
});
res.send({ postOne: postOne.length, postTwo: postTwo.length });

I can write like this for all of the 5 types, but I was wondering if there was any shorter way to do it so that I don't have to write the same code 5 times. 我可以为所有5种类型编写这样的代码,但是我想知道是否有任何更短的方法可以做到,因此我不必编写相同的代码5次。

Thanks! 谢谢!

const getPostWithType = (type) => Post.findAll({
  where: { 
    state: type
  }
});

Now you can await getPostWithType(1) instead. 现在您可以await getPostWithType(1) Or even better: 甚至更好:

const postTypes = [1,2,3,4,5];
const allPosts = await Promise.all(postTypes.map(getPostWithType));

// allPosts is now an array with the results. You can map it again to get the lengths
const allPostLengths = allPosts.map(p => p.length);

what about using an array? 那如何使用数组呢? Like below... 像下面...

 let promiseArray = []; for (let i = 1; i <= 5; i++) { let promise = Post.findAll({ where: { state: i } }); promiseArray.push(promise); } Promise.all(promiseArray).then(function(response) { //Do whatever... }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM