AnswerBun.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!

Related Questions

Cannot append option for select form

1  Asked on November 20, 2021 by nguyn-v

   

Constructors with the same primitive type as parameter

3  Asked on November 18, 2021 by arjun-singh

   

Python regex for numbers between 0-63

3  Asked on November 18, 2021 by perplexityy

   

How can I retrieve many values of a same field in a GET request

2  Asked on November 18, 2021 by user2424634

       

Can i know why my while loop is not working?

0  Asked on November 18, 2021 by niranjan-kumar

 

Moment JS days difference issue

1  Asked on November 18, 2021

   

How to update the value of a prop upon a state change in React

2  Asked on November 18, 2021 by alopez02

 

reload div without refresh page

1  Asked on November 18, 2021 by kemar-aim

         

Convert heirachy to dict of lists

0  Asked on November 18, 2021 by himabindu

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir