TransWikia.com

Sequelize - N:M Association Count Number of Included Model with Condition

Stack Overflow Asked by cylee on December 4, 2020

I have two models: Articles and Tags. These models are associated to each other by belongsToMany, so an article may have many tags, and tags can be used by many articles.

models

Articles.belongsToMany(Tags, {
    foreignKey: 'articleId', 
    as: 'tags', 
});

Tags.belongsToMany(Articles, {
    foreignKey: 'tagId', 
    as: 'articles', 
});

When querying, I need to get articles that has searchTag as tag, but get all tag information associated to article.

What I tried is:

const articles = await Articles.findAll({
    include: [{
        model: Tags, 
        as: 'tags', 
        where: {
            tag: searchTag, 
        }, 
        attributes: ['id', 'tag'], 
        required: true, 
    }], 
    where: { 
        // querying condition
    }, 
});

but this code gets the matching tag only, which fails to get all tags that belongs to the article.

Another solution I thought was to check if any tag that tag=searchTag exists in tags, but I have no idea how to fit this condition into sequelize object. What is the proper way to fit this condition into sequelize object? Or any other way to solve this problem other than getting all ids of articles that has searchedTag and get all articles based on the ids?

One Answer

You have to query for your searchTag in the top where clause.

const articles = await Articles.findAll({
    include: [{
        model: Tags, 
        as: 'tags', 
        // where: {
        //    tag: searchTag, 
        // }, 
        attributes: ['id', 'tag'], 
        required: true, 
    }], 
    where: { 
       $tags.id$': searchTag // <-- New
    }, 
});

By querying inside the include part, you get only the filtered tags like you described in your post.

Answered by Sven 31415 on December 4, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP