Sequelize 将 2 个查询组合为 sub where
Sequelize combine 2 queries as sub where
我有 2 个表 SocialPostEntity
和 ResearchEntity
。
ResearchEntity
有一个字段 relatedId
代表 SocialPostEntity.id
.
在我的映射中,ResearchEntity.relatedId
未映射,出于抽象原因,它只是一个整数。也没有外键。
我想在单个查询中包含以下内容:
select * from ResearchEntity where relatedId in (select id from SocialPostEntity);
目前,我已经在 2 个不同的查询中解决了它,这根本没有效率:
const fromPosts = await SocialPostEntity.findAll({ attributes: ['id'], where: { status: 1 } });
const allRelated = await ResearchEntity.findAll({ where: { postId: fromPosts.map(x => x.id) } });
不想用原生SQL字符串查询,想用sequlize查询API.
是否可以将“in”语句和 select 结合起来? in (select id from SocialPostEntity)
?
谢谢
此功能请求仍处于打开状态:https://github.com/sequelize/sequelize/issues/9509。
documentation refers to the sequelize.literal
utility to perform subqueries, which is the approach used by similar questions:
const subquery = sequelize.dialect.queryGenerator.selectQuery(SocialPostEntity.tableName, {
attributes: ['id'],
where: { status: 1 }
}).slice(0, -1);
const allRelated = await ResearchEntity.findAll({
where: { postId: { [Op.in] : sequelize.literal(`( ${subquery} )`) } }
});
我有 2 个表 SocialPostEntity
和 ResearchEntity
。
ResearchEntity
有一个字段 relatedId
代表 SocialPostEntity.id
.
在我的映射中,ResearchEntity.relatedId
未映射,出于抽象原因,它只是一个整数。也没有外键。
我想在单个查询中包含以下内容:
select * from ResearchEntity where relatedId in (select id from SocialPostEntity);
目前,我已经在 2 个不同的查询中解决了它,这根本没有效率:
const fromPosts = await SocialPostEntity.findAll({ attributes: ['id'], where: { status: 1 } });
const allRelated = await ResearchEntity.findAll({ where: { postId: fromPosts.map(x => x.id) } });
不想用原生SQL字符串查询,想用sequlize查询API.
是否可以将“in”语句和 select 结合起来? in (select id from SocialPostEntity)
?
谢谢
此功能请求仍处于打开状态:https://github.com/sequelize/sequelize/issues/9509。
documentation refers to the sequelize.literal
utility to perform subqueries, which is the approach used by similar questions:
const subquery = sequelize.dialect.queryGenerator.selectQuery(SocialPostEntity.tableName, {
attributes: ['id'],
where: { status: 1 }
}).slice(0, -1);
const allRelated = await ResearchEntity.findAll({
where: { postId: { [Op.in] : sequelize.literal(`( ${subquery} )`) } }
});