suchen

Heim  >  Fragen und Antworten  >  Hauptteil

Wie kann ich diese Abfrage in Sequelize ausführen?

<p><pre class="brush:php;toolbar:false;">SELECT * VON 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>Wie führe ich diese MySQL-Abfrage in sequelize – Node js aus, ohne die ursprüngliche Abfrage zu verwenden? </p>
P粉354602955P粉354602955450 Tage vor481

Antworte allen(2)Ich werde antworten

  • P粉245003607

    P粉2450036072023-09-06 00:38:24

    如果您的模型结构类似于 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);
       }

    现在尝试一下,我希望这能解决您的问题。

    Antwort
    0
  • P粉300541798

    P粉3005417982023-09-06 00:00:17

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

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

    Antwort
    0
  • StornierenAntwort