我有一个Sequelize查询,我的目标是拥有所有数据项目,但只有那些项目状态与当前状态ID匹配的项目,后者嵌套在另一个模型CodePhaseType中.
以下是目前的关系:
db.project.hasMany(
db.projectStatus,
{ foreignKey: 'project_id' }
);
db.project.hasMany(
db.projectStatus,
{ foreignKey: 'project_status_id',sourceKey: "current_project_status_id",
as: 'currentId' }
);
db.projectStatus.belongsTo(
db.codePhaseType,
{ foreignKey: 'code_phase_type_id' }
);
db.codePhaseType.belongsTo(
db.codeStatusType,
{ foreignKey: 'code_status_type_id' }
);
db.codePhaseType.belongsTo(
db.codeProjectType,
{ foreignKey: 'code_project_type_id' }
);
这是我try 的查询:
Project.findAll({
where: where,
limit,
offset,
separate: true,
attributes: [
"project_id",
"project_name",
"description",
"onbase_project_number",
"created_date",
'code_project_type_id',
'current_project_status_id',
],
include: [
{
model: ProjectStatus,
as: 'currentId',
include: {
model: CodePhaseType,
where: { code_status_type_id: +filter },
}
}
]
,
order: [['created_date', 'DESC']]
})
通过这个查询,我获得了所有匹配其中包含CodePhaseType的WHERE条件的项目. 尽管如此,问题在于分页. 偏移值的计算方法如下所示: 常量偏移量=(第-1页)*限制;
假设我查询第一页,限制为100.我有38个项目. 所以,如果我得到第4页,限制5,我应该得到项目,但它是空的.
生成的查询如下:
SELECT
[project].*,
...
[project].[code_project_type_id],
[project].[current_project_status_id]
FROM (
SELECT TOP 15 * FROM (
SELECT ROW_NUMBER() OVER (
ORDER BY [project].[created_date] DESC
) as row_num, *
FROM [project] AS [project]) AS [project]
WHERE row_num > 45
) AS [project]
WHERE (
SELECT TOP 1 [currentId].[project_status_id]
FROM [project_status] AS [currentId]
INNER JOIN [code_phase_type] AS [code_phase_type] ON [currentId].[code_phase_type_id] = [code_phase_type].[code_phase_type_id] AND [code_phase_type].[code_status_type_id] = 1
WHERE (
[currentId].[project_status_id] = [project].[current_project_status_id]
)
) IS NOT NULL
ORDER BY [project].[created_date] DESC
) AS [project]
LEFT OUTER JOIN [project_cost] AS [project_costs] ON [project].[project_id] = [project_costs].[project_id]
LEFT OUTER JOIN ( [project_status] AS [currentId]
INNER JOIN [code_phase_type] AS [currentId->code_phase_type] ON [currentId].[code_phase_type_id] = [currentId->code_phase_type].[code_phase_type_id]
AND [currentId->code_phase_type].[code_status_type_id] = 1 ) ON [project].[current_project_status_id] = [currentId].[project_status_id]
ORDER BY [project].[created_date] DESC;
因此,分页段似乎在条件之前,所以它不能很好地工作.
我用的是5.21.7的Sequelize版本.