[英]How to translate mysql query to sequelize orm
我需要用sequelize執行這個多LEFT JOIN查詢:
SELECT movie, genre FROM `yt_movies` M
LEFT JOIN `genres_link` GL ON M.id = GL.movie_id
LEFT JOIN `genres` G ON GL.genre_id = G.id
WHERE M.id = 1098
我試過了
const YtMovies = db.yt_movies;
const Genres = db.genres;
const GenresLink = db.genres_link;
YtMovies.hasMany(GenresLink, { as: 'GL', foreignKey: 'movie_id' });
YtMovies.hasMany(Genres, { as: 'G', foreignKey: 'genre' });
const res = await db.yt_movies.findAll({
attributes: ['movie'],
where: { id: movie_id },
include: [
{
model: db.genres_link,
as: 'GL',
required: false,
attributes: ['genre_id'],
},
{
model: db.genres,
required: false,
as: 'G',
attributes: ['genre'],
},
],
});
返回的查詢看起來像
SELECT
`yt_movies`.`id`,
`yt_movies`.`movie`,
`GL`.`id` AS `GL.id`,
`GL`.`genre_id` AS `GL.genre_id`,
`G`.`id` AS `G.id`,
`G`.`genre` AS `G.genre`
FROM `yt_movies` AS `yt_movies`
LEFT OUTER JOIN `genres_link` AS `GL` ON `yt_movies`.`id` = `GL`.`movie_id`
LEFT OUTER JOIN `genres` AS `G` ON `yt_movies`.`id` = `G`.`genre`
WHERE `yt_movies`.`id` = 1098;
在最后兩個字符串中我們可以看到它與yt_movies
使用ON但我希望它與genres_link
一起使用ON
LEFT JOIN `genres` AS G ON GL.genre_id = G.id <-- expected
我想我真的不理解表關聯並搞砸了hasMany或者我想念另一個聲明
表格看起來像
yt_movies
| id | movie | pj | pq|
|----|---------|----|---|
| 1 |Avatar | | |
| 2 |Predator | | |
| 3 |... | | |
genres_link
| id | genre_id| movie_id |
|----|---------|----------|
| 1 | 12 | 1 | // avatar
| 2 | 13 | 2 | // predator
| 3 | 14 | 2 | // predator
流派
| id | genre |
|----|----------|
| 12 | action |
| 13 | thriller |
| 14 | horror |
我所做的只是設法執行第一次LEFT JOIN ...添加第二次包括沒有幫助,我害怕即使在閱讀文檔之后我也沒有真正地解決表格關聯:
我想我需要使用belongsToMany,但此刻我不明白如何:))
我感謝所有的幫助! 謝謝,哈利普!
要加入A-> B-> C,您應該將C的include包含在B的include中,例如
A.findAll({
include: [
{
model: B,
include: [
{model: C}
]
}
]
})
但是,如果表genres_link比電影流派的PK外沒有其他的屬性,然后使用通過 。
YtMovies.belongsToMany(Genres, {through: GenresLink, foreignKey: 'movie_id' });
Genres.belongsToMany (YtMovies,{through: GenresLink, foreignKey: 'genre_id '});
YtMovies.findAll({
include: [
{
model: Genres,
required : true,
through: GenresLink
}
]
});
手冊中有關於此主題的一些有用信息......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.