I've got to rewrite this SQL to Sequilize:
SELECT table1.id, table1.name,
(SELECT COUNT(*) FROM table2 WHERE table2.t1_id = table1.id) AS t1_count
FROM table1 WHERE .... LIMIT ..... OFFSET .....;
Thanks:)
To generate the exact SQL in your example use sequelize.literal()
to generate the subquery.
const result = await Table1.findByPk(id, {
attributes: [
'id',
'name',
[
sequelize.literal(`(
SELECT COUNT(table2.id)
FROM table2
WHERE table2.id = table1.t1_id
)`),
't1_count',
],
],
where: {
// ...
},
limit: {
// ...
},
offset: {
// ...
},
});
You can also do this by using a LEFT JOIN
and then using sequelize.fn()
to call COUNT()
on the joined results.
const result = await Table1.findByPk(id, {
attributes: [
'id',
'name',
[
sequelize.fn('COUNT', sequelize.col('table2.id')),
't1_count',
],
],
include: {
model: Table2,
attributes: [],
where: {
id: {
[Op.col]: sequelize.col('table1.t1_id'),
},
},
required: false,
},
where: {
// ...
},
limit: {
// ...
},
offset: {
// ...
},
});
SELECT id, name, COUNT(table2.id)
FROM table1
LEFT JOIN table2 ON table2.id = table1.t1_id
WHERE .... LIMIT ..... OFFSET .....;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.