Mysql 如何在sequelize的子模型中添加条件,这些条件会影响FindCountAll中的父模型?
在sequelize中,我想在FindCountAll调用子模型中添加一个条件。如果条件为false,则应影响父模型,findAndCountAll应返回数组长度0。目前,仅该子模型的数组长度为0,其余父模型将返回 我在分享的代码中添加了更多细节。 我的代码是这样的:Mysql 如何在sequelize的子模型中添加条件,这些条件会影响FindCountAll中的父模型?,mysql,node.js,express,sequelize.js,sequelize-cli,Mysql,Node.js,Express,Sequelize.js,Sequelize Cli,在sequelize中,我想在FindCountAll调用子模型中添加一个条件。如果条件为false,则应影响父模型,findAndCountAll应返回数组长度0。目前,仅该子模型的数组长度为0,其余父模型将返回 我在分享的代码中添加了更多细节。 我的代码是这样的: 好的,我找到了解决方案,但添加了一个带有连接的原始查询,我在需要的地方添加了我所需的条件,并获取了主模型的id。然后,我使用sequelize在where子句中添加这些ID来获取数据。我的代码现在看起来像这样 const { li
好的,我找到了解决方案,但添加了一个带有连接的原始查询,我在需要的地方添加了我所需的条件,并获取了主模型的id。然后,我使用sequelize在where子句中添加这些ID来获取数据。我的代码现在看起来像这样
const { limit, offset } = dbHelpers.GetPagination(
req.query.limit,
req.query.offset
);
let querySting = "(SELECT count(DISTINCT p.id) FROM ModelA p " +
"JOIN ModelB cp ON cp.pId = p.id " +
"JOIN ModelC cs ON cs.cpId = cp.id " +
"JOIN ModelD ms ON ms.csId = cs.id " +
"LEFT JOIN ModelE sa ON sa.msId = ms.id " +
"LEFT JOIN ModelF pp ON pp.msId = ms.id " +
"LEFT JOIN ModelG sta ON sta.ppId = pp.id " +
"LEFT JOIN ModelH ol ON ol.cdId = cd.id " +
"WHERE " //you can add your conditions here
+ " ORDER BY p.id desc LIMIT " + offset + ", " + limit + ")"
const rawQuery = await models.sequelize.query(querySting,
{ type: QueryTypes.SELECT })
const Ids = rawQuery.map(result => result.id)
const results = await models.ModelA.findAndCountAll({
where: {
id: Ids
},
include: [
{
model: models.ModelB,
as: "ModelB",
include: [
{
model: models.ModelC,
separate: true,
},
{
model: models.ModelD,
separate: true,
include: [
{
model: models.ModelE,
separate: true,
{
model: models.ModelF,
separate: true,
},
],
},
],
},
],
},
{
model: models.ModelG,
include: [
{
model: models.ModelH,
as: "ModelH",
},
],
},
],
});
const { limit, offset } = dbHelpers.GetPagination(
req.query.limit,
req.query.offset
);
let querySting = "(SELECT count(DISTINCT p.id) FROM ModelA p " +
"JOIN ModelB cp ON cp.pId = p.id " +
"JOIN ModelC cs ON cs.cpId = cp.id " +
"JOIN ModelD ms ON ms.csId = cs.id " +
"LEFT JOIN ModelE sa ON sa.msId = ms.id " +
"LEFT JOIN ModelF pp ON pp.msId = ms.id " +
"LEFT JOIN ModelG sta ON sta.ppId = pp.id " +
"LEFT JOIN ModelH ol ON ol.cdId = cd.id " +
"WHERE " //you can add your conditions here
+ " ORDER BY p.id desc LIMIT " + offset + ", " + limit + ")"
const rawQuery = await models.sequelize.query(querySting,
{ type: QueryTypes.SELECT })
const Ids = rawQuery.map(result => result.id)
const results = await models.ModelA.findAndCountAll({
where: {
id: Ids
},
include: [
{
model: models.ModelB,
as: "ModelB",
include: [
{
model: models.ModelC,
separate: true,
},
{
model: models.ModelD,
separate: true,
include: [
{
model: models.ModelE,
separate: true,
{
model: models.ModelF,
separate: true,
},
],
},
],
},
],
},
{
model: models.ModelG,
include: [
{
model: models.ModelH,
as: "ModelH",
},
],
},
],
});