0

I am looking to return all articles from the database associated with one or more keywords, but I am not sure there right way to go about this?

I am using Sequelize 3.x, with node.js 3.7.0.

The data model looks at follows:

const Article = sequelize.define('article', {
                     ...
                }

const Keyword = sequelize.define('keyword', {
                     name: Sequelize.STRING,
                     lang: Sequelize.STRING  
                }

const ArticleKeyword = sequelize.define('article_keyword', {
                     articleId: Sequelize.INTEGER,
                     keywordId: Sequelize.INTEGER  
                }

(Article).belongsToMany(
    Keyword, { through: ArticleKeyword, as: 'keyword' });

(Keyword).belongsToMany(
    Article { through: ArticleKeyword, as: 'article' });

Then the query I tried:

var keywordFilter;
if (req.body.keywords) {
    var keywords = req.body.keywords);
    if (typeof keywords === 'string') {
        keywords = keywords.split(/ *, */);
    }        
    keywordFilter = { name: { $in: keywords } };
}

Article.findAll({
    where: {
        deleted: false                
    },
    include: [{
        model: Keyword,
        as: 'keywords',
        where: keywordFilter,
        attributes: ['name'],
        through: {
            attributes: []
        }
    }]
}).then(function(articles) {
   ...
});

The issue I am finding here is rather than selecting just the articles with the matching keywords it returns all the articles and then simply selects the keywords specified in the query for the results.

Can anyone suggest the right way to go about this?

Andre M
  • 6,649
  • 7
  • 52
  • 93

1 Answers1

0

Hi can you try passing

require:true 

in the include block for inner join and check

Ref : https://stackoverflow.com/a/31680398/4583460

Community
  • 1
  • 1
Keval
  • 3,246
  • 20
  • 28