我正在使用Node.js,Express和MySQL来构建项目。 我使用以下代码创建了两个餐桌餐厅和评论:
CREATE TABLE restaurants (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
image_url VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
INSERT INTO restaurants (name, description, image_url) VALUES
(
'test 1',
'beautiful!!!!',
'https://xxx.jpg'
),
(
'test 2',
'beautiful!!!!',
'https://xxx.jpg'
),
(
'test 3',
'beautiful!!!!',
'https://xxx.jpg'
);
CREATE TABLE comments (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
commentText TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW(),
author VARCHAR(255) NOT NULL,
restaurant_id INT NOT NULL,
FOREIGN KEY (restaurant_id)
REFERENCES restaurants(id)
ON DELETE CASCADE
);
INSERT INTO comments (commentText, author, restaurant_id) VALUES
('test for comment 1', 'aaron', '1'),
('test for comment 1', 'bob', '1'),
('test for comment 2', 'frank', '2'),
('test for comment 2', 'lisa', '2'),
('test for comment 3', 'aaron', '3'),
('test for comment 3', 'bob', '3');
显示具有名称,图像,描述和评论的特定餐厅的路线代码如下:
app.get("/restaurants/:id", function(req, res) {
var id = req.params.id;
connection.query('SELECT * FROM restaurants INNER JOIN comments ON (restaurants.id = comments.restaurant_id) WHERE restaurants.id = ? ',[id], function(err, result){
if (err) throw err;
var findRestaurant = {
name: result[0].name,
image_url: result[0].image_url,
description: result[0].description,
commentText: result.commentText,
author: result.author
};
res.render("show", {restaurant: findRestaurant});
});
});
show.ejs代码为
<% include partials/header %>
<h1><%= restaurant.name %></h1>
<img src = " <%= restaurant.image_url %>">
<p><%= restaurant.description %> </p>
<% for (var i = 0; i < restaurant.length; i++) { %>
<p><strong><%= restaurant[i].author %></strong> - <%= restaurant[i].commentText %></p>
<% } %>
<% include partials/footer %>
除了页面上没有显示注释(显示名称,图像和描述在显示页面上正确显示,但没有注释)之外,一切正常。
通过
'SELECT * FROM Restaurants INNER JOIN评论开启(restaurants.id = comments.restaurant_id)WHERE Restaurants.id =吗? '
应该选择带有相关注释的当前餐厅,但是将数据传递到ejs文件时似乎存在一些问题。 预先感谢任何可以帮助我解决此问题的人。