0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Nodejs のためになる話、ORMライブラリを使わずにsqlの内部結合

Posted at

どうもこんにちは、マッスルエンジニアの真です。

今回も有益なお話をさせてもらえたらと思います。

内容は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(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 = ?, [2021, 2, true]);
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});
}));

コードだけ記載するので、もし質問、ご指摘、こんなやりかたもあるよというかた
ぜひおしえてください!

それでは

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?