์๋ ํ์ธ์, Knexjs ํ์ ํ๋ฅญํ ์์ ์ ๋๋ค. ๋๋ ๋ค ๋๋ค ๊ด๊ณ๋ฅผ ๊ฐ๋ ํ๋์ ์์ ์๋ฅผ ์ฌ์ฉํ์ฌ ORM์ ํตํด knexjs๋ฅผ ์๋ํ๊ณ ์์ต๋๋ค. ์์ ๋ Authors and Books์ ๊ฒฝ์ฐ auhtors ํ ์ด๋ธ๊ณผ book ํ ์ด๋ธ์ author_books ํ ์ด๋ธ์ ํตํด ๋ค ๋๋ค ๊ด๊ณ๋ฅผ ๊ฐ์ต๋๋ค. ๋๋ ๋ชจ๋ ์ ์์ ํจ๊ป ํน์ ์ฑ ์ ์ป๊ณ ์ถ์ต๋๋ค. ์๋๋ ์์ ๊ฒฐ๊ณผ๋ฅผ ์ ๊ณตํ๋ ์์ ์ฟผ๋ฆฌ์ ๋๋ค. ํ์ง๋ง Knexjs๋ฅผ ์ฌ์ฉํ์ฌ์ด ์ฟผ๋ฆฌ๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ์ ์ป์ง ๋ชปํฉ๋๊น? ์ด๋ค ๋์์ ์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค.
์ฐธ๊ณ : ์ ๋ ์๋ฐ ์คํฌ๋ฆฝํธ ES6๊ณผ ํจ๊ป Knexjs๋ฅผ ์ฌ์ฉํ๊ณ ์์ต๋๋ค.
SELECT `book`.`id` , `book`.`title` , `authors`.`id` AS `authors.id` , `authors`.`name`
AS `authors.authorname` , `authors.author_books`.`book_id`
AS `authors.author_books.bookId` , `authors.author_books`.`author_id`
AS `authors.author_books.author_id`
FROM `books` AS `book`
LEFT OUTER JOIN (
`author_books` AS `authors.author_books`
INNER JOIN `authors` AS `authors` ON `authors`.`id` = `authors.author_books`.`author_id`
) ON `book`.`id` = `authors.author_books`.`book_id`
WHERE `book`.`id` =1
์ด๊ฒ์ Knexjs๋ฅผ ์ฌ์ฉํ์ฌ ๋น๋ํ๋ ค๋ ์ฟผ๋ฆฌ์ ๋๋ค.
this.Knex('books as book')
.leftOuterJoin('author_books as authors.author_books', function(){
// How could I nest INNER JOIN in LEFT OUTER JOIN
this.on('book.id', 'authors.author_books.book_id')
}).select('book.id', 'book.title', 'authors.id as authors.id'
, 'authors.name as authors.name', 'authors.author_books.book_id as authors.author_books.book_id'
, 'authors.author_books.author_id as authors.auhtor_books.author_id')
.where('book.id', id)
๋ด๊ฐ ํ๋ ธ๋ค๋ฉด ์๋ ค์ฃผ์ธ์?
๋ฌธ์ ๋ knexjs๋ฅผ ์ฌ์ฉํ์ฌ ์กฐ์ธ ์ฟผ๋ฆฌ๋ฅผ ์ค์ฒฉํ๋ ๋ฐฉ๋ฒ์ ๋๋ค. knex๋ฅผ ์ฌ์ฉํ์ฌ Left ๋๋ Right JOIN์ผ๋ก ์ค์ฒฉ ๋ ๋ด๋ถ ์กฐ์ธ, ๊ทธ๋ฌ๋ฉด knex๊ฐ ์์ Query : ์น์ ์ ํ์๋๋๋ก SQL ์ฟผ๋ฆฌ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
@saurabhghewari ์ด ์ง๋ฌธ์ ๋ํ ํด๊ฒฐ์ฑ ์ ์ฐพ์์ต๋๊น? ๋น์ทํ ์ผ์ํ๋ ค๊ณ ํฉ๋๋ค.
knex๊ฐ ์ค์ฒฉ ์กฐ์ธ์ ์ง์ํ๋์ง ํ์คํ์ง ์๋ค๊ณ ๋งํด์ผํฉ๋๋ค.์ด ๊ฒฝ์ฐ์ ๋ํ ํ ์คํธ ๋ ๋ฌธ์๋ฅผ ๋ณด์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ ์ง์๋์ง ์๋๋ค๊ณ ํ์ ํฉ๋๋ค. ์ด์ ๋ํ ๊ธฐ๋ฅ ์์ฒญ์ ์ถ๊ฐํ์ญ์์ค.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
๋ฌธ์ ๋ knexjs๋ฅผ ์ฌ์ฉํ์ฌ ์กฐ์ธ ์ฟผ๋ฆฌ๋ฅผ ์ค์ฒฉํ๋ ๋ฐฉ๋ฒ์ ๋๋ค. knex๋ฅผ ์ฌ์ฉํ์ฌ Left ๋๋ Right JOIN์ผ๋ก ์ค์ฒฉ ๋ ๋ด๋ถ ์กฐ์ธ, ๊ทธ๋ฌ๋ฉด knex๊ฐ ์์ Query : ์น์ ์ ํ์๋๋๋ก SQL ์ฟผ๋ฆฌ๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.