Home > Blockchain >  How to set a minimum number of rows to return from an association with Sequelize
How to set a minimum number of rows to return from an association with Sequelize

Time:12-11

Let's say I have the following include in a getter function in sequelize to get some data. How can I exclude the 'videos' array from the result if there is no videos in that category or set a minimum amount of rows needed to return? Right now the result prints out each category with their respective videos and an empty videos array if there are none but i want it to exlude that category entirely if theres no videos. I tried setting the required property on the videos model include but that didn't work. I couldn't find anything on this so if someone who knows how to do this could chip in I'd really appreciate it. Thanks!

    include: [
          {
             model: models.category,
             include: models.video,
          }
    ]

CodePudding user response:

I don't know how is your model but I will try to create a example to clarify you and adapt for your reality. To set a minimum results in your include you just insert limit with where clause in your include like it:

include: [
    {
      model: models.category,
      include: models.video,
      limit: 10,
      where: {
        // it's a simple subquery to select all category IDs that have at least 10 videos associated
        id: {
          [Op.in]: Sequelize.literal(
            "SELECT categoryId FROM videos GROUP BY categoryId HAVING COUNT(*) >= 10"
          ),
        },
      },
    },
  ];
  • Related