我想创建一个使用Sequelize的DSL返回非db模型的查询。我写了 raw 查询,如下所示:
instanceMethods: {
getHoursReport: function({from, to, companies}) {
let currentDate = new Date();
from = from || new Date(
currentDate.getFullYear(),
currentDate.getMonth(),
1
);
to = to || new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
0
);
let fromString = from.toISOString();
let toString = to.toISOString();
let companiesFilter = 'true';
if (typeof companies !== 'undefined' && companies.length > 0) {
companiesFilter = `c.id IN ('${companies.join("','")}')`;
}
// @todo: Use Sequelize DSL to make the query
const query = `
SELECT p.id as contractor,
string_agg(DISTINCT pr.name, ';') as projects,
round(sum(te.hours), 2) as "totalHours",
round(sum(te.hours * te.rate), 2) as "totalPay"
FROM person_company_roles pcr
JOIN companies c
ON pcr."companyId" = c.id
JOIN projects pr
ON pr."clientId" = c.id
JOIN project_timesheets pt
ON pt."projectId" = pr.id
JOIN timesheet_entries te
ON pt.id = te."timesheetId"
JOIN people p
ON p.id = pt."contractorId"
WHERE pcr."personId" = '${this.id}' AND
pcr.role = 'owner' AND
te."entryDate"::date BETWEEN
'${fromString}'::date AND '${toString}'::date AND
${companiesFilter}
GROUP BY p.id;
`;
return sequelize.query(query, {
model: sequelize.models.hoursReport
}).then(
report => report[0]
);
}
}
在Sequelize docs中,查询是从模型构建的。所以,我不明白如何从 hoursReport 模型中创建查询。
任何帮助将不胜感激。
提前致谢