どうもこんにちは、マッスルエンジニアの真です。
今回も有益なお話をさせてもらえたらと思います。
内容はORMライブラリを使わずに内部結合させて、データベースの従属関係もつくっちゃうって
やつです。
早速説明します。
app.get('/staff_shift', wrap(async (req: Request, res: Response, next: NextFunction) => {
//データベースの構成は無視してください
const staffs: {
id: number,
name: string,
email: string,
date: number,
shift:string,
}[] = await pool.query(
, [2021, 2, true]);
SELECT
user.id AS id,
user.name AS name,
user.email AS email,
staff.data AS date,
staff.shift AS shift
FROM user
INNER JOIN staff ON (user.id = staff.staffId)
WHERE
staff.year = ?
AND
staff.month = ?
AND
staff.check = ?
const formattedStaffs: {
id: number,
name: string,
email: string,
shifts: {
date: number,
shift:string,
}[]
}[] = [];
//この下からが肝かなと、、、、
staffs.map(staff => {
const exist_data = formattedStaffs.find(v => v.id === staff.id);
if (exist_data) {
exist_data.shifts.push({
date: staff.date,
shift:staff.shift,
});
} else {
formattedStaffs.push({
id: staff.id,
name: staff.name,
email: staff.email,
shifts: [
{
date: staff.date,
shift:staff.shift,
},
]
});
}
});
res.json({staffs});
}));
コードだけ記載するので、もし質問、ご指摘、こんなやりかたもあるよというかた
ぜひおしえてください!
それでは