|
我有以下查询,将数据插入到多对多联接表中
/ `! e0 u0 G% e4 r3 n+ p2 bINSERT INTO playlist_genre(playlist_id, genre_id); \/ E7 J* o" q: s0 W3 p" z
VALUES (${playlistId}, ${genre1Id}),
8 s" n0 X2 _, I9 ]4 X (${playlistId}, ${genre2Id}),3 V& P1 u% E' \8 x0 i/ f. x5 `, }
(${playlistId}, ${genre3Id})
9 F3 x6 B# A1 Q Z( T# B J);
. `3 l5 @/ R. F x% P' _但是,我遇到的问题是用户并不需要这些值genre2Id和genre3Id,因此可以是anINTEGER或NULL。
1 V2 A9 {3 O) b6 ]8 @# K我正在尝试找到一种方法来写入此相同的查询,但因此仅在存在值的情况下才插入。两列都有NOT NULL约束。
1 S$ l+ S( V- |编辑 :' A; [4 k9 K( A; J$ q( ^* t
这是我的播放列表课程
: Y) L1 @* p# l) _- Wclass Playlist {* Y' Q2 Y- x+ [! [3 e
constructor(playlist) {# s M- n( x; e7 [! ]& D& H& D6 q/ m5 L/ L
// required fields
& J& r y4 u+ ? this.title = playlist.title;
& {: } l5 \4 x this.playlistType = playlist.playlistType;- b) c3 u( C6 }9 j( p/ R
this.userId = playlist.userId;( m4 N) Y% E0 d5 h7 j
this.numberOfTracks = playlist.numberOfTracks;* e K* i4 r4 q
this.lengthInSeconds = playlist.lengthInSeconds;
5 D& ~9 }! X5 }; W! | this.genre1Id = playlist.genre1Id;
5 K5 a2 O' d; F0 p; G // not required fields
, n7 F9 A r% g4 O/ N2 a _ this.genre2Id = playlist.genre2Id || null;0 K+ m7 }7 O+ T4 P# }+ ?7 z
this.genre3Id = playlist.genre3Id || null;
* ?# ` W$ ?3 }% W. r6 D) t this.description = playlist.description || null;
; z; m3 E+ x5 p8 `1 W* d; g* E, W this.releaseDate = playlist.releaseDate || null;
& ^- R% _0 |9 K6 ~1 J" Y/ ~9 l }
% o" U& q P5 _" Z% x" @$ \ save() {
$ t7 s0 B4 Q* {4 w5 l" E( s; D return new Promise((resolve, reject) => {
& m0 x/ J7 ?' g8 o8 g db.one(sqlCreatePlaylist, this). e' t* D6 H# C$ s9 k$ y
.then((insertedPlaylist) => {9 |% l! D% R; }) h4 E Y0 b
// Here is where i want to use insertedPlaylist's id 7 e- I6 E" U0 ^
// to insert data into 'playlist_genre' table- |" m' j1 n$ M
resolve(insertedPlaylist);
! o% _. u) I1 P4 C. |! A) H })
, p8 Z0 c4 W' P6 M .catch(error => reject(error));& u q% O6 K Z; F& ]. {
});4 e7 b6 A4 ?: p" Y( ]
}9 x3 I) h# w: }& t
这是sqlCreatePlaylist的样子
& `% w# [0 g* ~- EINSERT INTO playlists(
2 r# L) A) X6 S, L8 b1 ^8 a user_id,# K. T3 X& ^7 l: m. @2 }+ f
title,
* S6 U: w4 w- P playlist_type,9 F- o' l% t6 c! q
number_of_tracks," ~4 E4 e) u4 W) a) e1 @
duration,5 [4 Q& I6 i. V( s
description,
5 [; E$ c- A8 w% B9 V release_date# \. F" B# z! S4 F3 X) r' M4 V
)8 @/ y2 |4 e6 m o
VALUES(* k+ c; Y2 @$ p# }$ q) X0 b
${userId},' k* U$ A( }5 f2 M% N
${title},
+ G2 z" t3 z {9 [1 `9 d, I- a- N ${playlistType},
' Y- Q6 z6 H& m+ ~ ${numberOfTracks},( m5 @2 F" N- N. K
${lengthInSeconds},
# P! V5 g1 W; O% Z ${description},
7 N% D* N9 q, k4 j! ^3 Y3 R ${releaseDate}
1 I4 {( Z( o f. v)/ P" r- q5 d0 e% s! F1 k
RETURNING *;) F2 z0 |2 l' w$ J# T9 o
- W, H9 {9 ]; z; h. e# g
解决方案: |
|