投稿に対してコメントをしたユーザー名を表示したいです。
現在投稿に対するコメントは表示することはできています。がユーザー名を表示することができていません。
inner joinを使うのだと思いますが、どこにどう使っていいかが分かっていません。。
postが投稿で、commentがその投稿に対すコメントになります。
router.get("/",(req,res) =>{ console.log(req.query); const postId = req.query.id; const query = `SELECT * FROM posts where id = ${postId}` connection.query(query, (err,post_rows) =>{ const query = `SELECT * FROM comments where post_id = ${postId} ORDER BY created_at DESC`; // const query = "SELECT * FROM comments INNER JOIN users ON comments.user_id = users.id"; connection.query(query,(err,comment_rows) =>{ res.render('comment',{postList: post_rows, commentList: comment_rows}); }); }); });
router.post("/", (req,res)=>{ const userId = req.session.user_id? req.session.user_id: 0; const postId = req.body.id; const comment = req.body.comment; const createdAt = moment().format('YYYY-MM-DD HH:mm:ss'); const query = 'INSERT INTO comments (user_id, post_id, comment, created_at) VALUES ("' + userId + '",'+'"' + postId + '", ' + '"' + comment + '","' + createdAt + '")'; connection.query(query,(err,rows) =>{ res.redirect(`/comment?id=${postId}`); }); });
yuxkiさん、aachyeeさんありがとうございます!
expressです!!
```
CREATE TABLE `comments` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`post_id` int(11) DEFAULT NULL,
`comment` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
)
```
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL DEFAULT '',
`email` varchar(255) NOT NULL DEFAULT '',
`password` varchar(255) NOT NULL DEFAULT '',
`prefecture` varchar(255) DEFAULT NULL,
`createdAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`updatedAt` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
```
```
あ、すいません。SQLの問題っぽいですね。退散します><
回答2件
あなたの回答
tips
プレビュー