skip to Main Content
SELECT * 
FROM item_master 
WHERE project_id IN (SELECT id FROM project_master 
                     WHERE workspace_id in (SELECT id FROM workspace_master 
                                            WHERE company_id = 4));

How can I do this mysql query in sequelize – node js without using raw query?

2

Answers


  1. Chosen as BEST ANSWER
    const item = await Item.findAll({
        where: {
            status: { [Op.ne]: 99 },
            '$project.workspace.company_id$': { [Op.eq]: req.user.companyId }
        },
        include: {
            model: Project,
            as: 'project',
            attributes: ['id'],
            include: {
                model: Workspace,
                as: 'workspace',
                attributes: ['id', 'companyId'],
                where: {
                    companyId: req.user.companyId
                },
            },
        }
    })
    

    This is working as I want.

    '$project.workspace.company_id$': { [Op.eq]: req.user.companyId }


  2. If your model structure is like item_master has many project_master, and project_master has many workspace_master, then the following sequelize query will be applied with async/await.

    As I edited my answer. As you said in comment, you have model structure like workspace has many projects and projects has many items. Then Sequelize query will be like:

        const getResult = async (workpace_id, company_id = 4) => {
          const result = await workspace_master.findAll({
          subQuery: false,
          include: [
            {
              model: project_master,
              as: 'project_masters', // this is your alias defined in model
              attributes: ['id','foo','bar'],
              include: [
                {
                  model: item_master,
                  as: 'item_masters', // this is your alias defined in model
                  attributes: ['id','foo','bar']
                }
              ]
            }
          ],
          where: {
             id: workspace_id,
             company_id: company_id
          }
        });
        
        if(!result || !result.length) return res.send('Something went wrong!');
        return res.send(result);
       }
    

    Now try this, I hope this will solve your issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search