简体   繁体   中英

Nesting multiple [Op.not] queries in a single where clause

I've got a filter that allows users to indicate themes and genres they would like removed from the search results. This is an OR, not AND situation, so if either a theme or a genre is matched, it should be removed from the pool.

If I run the query below with a single [Op.not] clause, the themes and genres filter correctly. When I attempt to combine them as show in the example, only the genres [Op.not] executes. I assume I've chained them incorrectly in the where clause?

Code Example

    //Variables to store filters from JSON body
    let sortBy = [req.body.galleryFilters.sortBy, 'ASC']
    let hiddenThemes = [];
    let hiddenGenres = [];

    //Parse the body for activeFilters create and array of Active Filters 
    req.body.galleryFilters.themes.forEach(theme => {
      if(theme.hidden === true) {
        hiddenThemes.push(theme.name)
      }
    })

    req.body.galleryFilters.genres.forEach(genre => {
      if(genre.hidden === true) {
        hiddenGenres.push(genre.name)
      }
    })

    //use variables above to create new playlist obje
    const playlists = await db.playlists.findAll({
      where: {
        [Op.not]: {
          themes: {
            [Op.overlap]: hiddenThemes
          },
        },
        [Op.not]: {
          genres: {
            [Op.overlap]: hiddenGenres
          },
        },
      },
      order: [[req.body.galleryFilters.sortBy, 'ASC']]
    });
  
    return res.send(playlists);
  
  }
});

I'm too inexperienced to give a thorough explanation but the revision below seems to work for now:

 const playlists = await db.playlists.findAll({
      where: {
        [Op.not]: {
          [Op.or]: {
            themes: { [Op.overlap]: hiddenThemes },
            genres: { [Op.overlap]: hiddenGenres },
          }
        }
      },
      order: [[req.body.galleryFilters.sortBy, 'ASC']]
    });

    return res.send(playlists);

  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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