我怎麼能在sequelize中執行這個查詢
P粉354602955
P粉354602955 2023-09-05 09:43:31
0
2
445
<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>如何在sequelize - Node js 中執行此 mysql 查詢而不使用原始查詢? </p>
P粉354602955
P粉354602955

全部回覆(2)
P粉245003607

如果您的模型結構類似於item_master 有許多project_master,並且project_master 有許多workspace_master,那麼以下sequelize查詢將與async/await一起應用。

當我編輯我的答案。正如您在評論中所說,您有模型結構,例如工作區有許多項目,項目有許多項目。然後 Sequelize 查詢將類似於:

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);
   }

現在嘗試一下,我希望這能解決您的問題。

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
            },
        },
    }
})

這正在按我想要的方式工作。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!