鍍金池/ 問答/數(shù)據(jù)庫  HTML/ sequelieJS選取數(shù)據(jù)庫語句

sequelieJS選取數(shù)據(jù)庫語句

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



   
   

求老司機(jī)如何寫成sequelize的語句?

回答
編輯回答
糖豆豆
    
    await organizationModel.findAll({
        where:{
            name: {
                $like: 'ext-%'
            }
        }
    }).then(ori => {
        // 這里需要修改,不能循環(huán)查詢數(shù)據(jù)庫
        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
        });
    });

};

2018年8月28日 05:38
編輯回答
尤禮
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}
    }
})
2018年6月24日 12:02