Node.js/Sequelize
[ORM] ๐ ์ํ๋ผ์ด์ฆ - ๋ค์ค ์กฐ์ธ ๋ฐฉ๋ฒ
์ธํ_
2022. 6. 5. 09:38
Sequelize ์ฌ๋ฌ JOIN
์ํ๋ผ์ด์ฆ ORM์ ์กฐ์ธ ๋ฐฉ๋ฒ์ ์ ๋ฆฌํด๋ณธ๋ค.
์ ๋งํ๋ฉด ์ฑ๋ฅ์ ์ํด์ ํ๋์ด์ ์กฐ์ธ์ ํ๋ ๊ฒ์ ํผํด์ผ ๋๋ ๊ฒ์ด ๋ง์ง๋ง, ์ฐ๊ด๋ ๋ฐ์ดํฐ๊ฐ ์ฌ๋ฟ ํ์ํ ๊ฒฝ์ฐ ์ด์ฉ์ ์์ด ๋ค์ค ์กฐ์ธ์ ํ ํ์์ฑ์ด ์๊ธด๋ค. (์ด๋ฅผ ๋ฐฉ์ง ํ๊ธฐ ์ํด ์ญ์ ๊ทํ๋ฅผ ์ํด์ผ ๋์ง๋ง..)
๋ค์ ์ฌ์ง์ ์์ ์ฝ๋์ ์ฐ์ธ erd ์ด๋ค. ๊ด๊ณ๋ฅผ ์๋ณด๊ณ ์กฐ์ธ ์์ ๋ฅผ ์ดํด๋ณด์.
์ํ๋ผ์ด์ฆ JOIN
- join 2 tables
const user = await User.findOne({
include: [{ // ์ํ๋ผ์ด์ฆ ์กฐ์ธ์ ๊ธฐ๋ณธ inner join
model: Comment, // joinํ ๋ชจ๋ธ
attributes: ['id'], // selectํด์ ํ์ํ ํ๋ ์ง์
where: {
id: 1, // on Comment.id = 1
},
}]
});
// ๋๋ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
const user = await User.findOne({ ... }); // ๋จผ์ user ์ฟผ๋ฆฌ๋ฅผ ์ป๊ณ
const comments = await user.getComments({ // user์ comments๋ฅผ ๊ด๊ณ๋งบ์ด getํ๋ค.
attributes: ['id'], // joinํด ๊ฐ์ ธ์ฌ comments๋ฅผ.id
where: {
id: 1, // comments๋ฅผ.id = 1
},
});
select users.*, comments.id
from users
inner join comments
on comments.id = users.id
where comments.id = 1
LIMIT 1;
์ํ๋ผ์ด์ฆ ๋ค์ค JOIN
- join 3 tables
- ํ๋์ table์ด ๋ค๋ฅธ ๋ table๊ณผ ๊ด๊ณ๋ฅผ ๋งบ์์๋
- A - B - C ์ด๋ ๊ฒ ์ฐ๊ฒฐ๋ ํ ์ด๋ธ์์ B๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ฐ์ ธ์ฌ ๋
const user = User.findOne({
where: { id : 123123 },
include: [
{
model: User,
attributes: ['id', 'nick'],
as: 'Followers',
},
{
model: User,
attributes: ['id', 'nick'],
as: 'Followings',
},
],
});
select users.*, Followers.id, Followers.nick, Followings.id, Followings.nick,
from users
inner join follow as Followers on users.id = Followers.followerId
inner join follow as Followings on users.id = Followings.followingId
where users.id = 123123
์ํ๋ผ์ด์ฆ ๋ค์ค ์ค์ฒฉ JOIN
- join 3 tables
- ๊ฐ table๋ผ๋ฆฌ ๋ง๋ค ๊ด๊ณ๋ฅผ ๋งบ์์๋, table์ table์ด ์ค์ฒฉํด์ ์กฐ์ธ
- A - B - C ์ด๋ ๊ฒ ์ฐ๊ฒฐ๋ ํ ์ด๋ธ์์ A๋ฅผ ๊ธฐ์ค์ผ๋ก ๊ฐ์ ธ์ฌ ๋
const posts = Hashtag.findOne({
where: { title: query },
include: [
{
model: Post,
attributes: [ ... ],
// include ์์ include
include: [
{
model: User,
attributes: ['id', 'nick'],
},
],
},
],
});
// ์ค์ฒฉ include๊ฐ ๋ณด๊ธฐ ์์ข๋ค๊ณ ์๊ฐํ๋ฉด, ๋ค์๊ณผ ๊ฐ์ด get๋ชจ๋ธ ๋ฌธ๋ฒ์ ์ด์ฉํด ํ๋ฒ ์กฐ์ธ์ ํ๊ณ , include๋ฅผ ์ฐ๋ฉด ๋ณด๋ค ๊ฐ๋
์ฑ์ด ๋์ด๋๋ค.
const hashtag = await Hashtag.findOne({ where: { title: query } });
let posts = [];
if (hashtag) {
posts = await hashtag.getPosts({ // hashtag.getPosts() => Hashtag ์ Post ์กฐ์ธ
include: [
{
model: User, // Post ์ User ์กฐ์ธ
attributes: ['id', 'nick'],
},
],
}); // hastags, posts, users ์ผ์ค ์กฐ์ธํด์ ๊ฐ์ ธ์จ๋ค.
}