sequelieJS选取数据库语句

// mysql原生语句
select * from user_organization where organization_id in(select id from organization where name like 'ext-%');



   
   

求老司机如何写成sequelize的语句?

阅读 2.7k
2 个回答
const Sequelize = require('sequelize');
const sequelize = new Sequelize(...);

sequelize.query( //原始查询
     'select * from user_organization where organization_id in(select id from organization where name like 'ext-%')' ,
     { type:Sequelize.QueryTypes.SELECT }
);

或者分两步简单查询:

const ids = await DBmodel.Organization.findAll({
    where: { name: {$like: 'ext-%'} },
    attributes: ['id']
})
const result = await DBmodel.User_organization.findAll({
    where: {
        organization_id: {$in: ids}
    }
})
    
    await organizationModel.findAll({
        where:{
            name: {
                $like: 'ext-%'
            }
        }
    }).then(ori => {
        // 这里需要修改,不能循环查询数据库
        Array.from(ori).forEach(record => {
            return userOrganizationModel.findAll({
                where: {
                    'organization_id':record.id
                }
            }).then(result => {
                console.log(result);
                ctx.json({
                    status: 100,
                    result
                });
            })
        });
        
    }).catch(err => {
        console.log(err);
        ctx.json({
            status: 101
        });
    });

};

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题