How can I execute this query in sequelize
P粉354602955
P粉354602955 2023-09-05 09:43:31
0
2
396
<p><pre class="brush:php;toolbar:false;">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));</pre> <p>How to execute this mysql query in sequelize - Node js without using original query? </p>
P粉354602955
P粉354602955

reply all(2)
P粉245003607

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 Applied together with async/await.

As I edit my answer. As you said in your comments you have model structure like workspace has many projects and project has many projects. Then the Sequelize query will look 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);
   }

Try it now, I hope this solves your problem.

P粉300541798
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 the way I want.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!