Я работаю в nodejs
и mysql 5.7
. У меня есть две таблицы:
a. products
b. productsimages
таблица товаров
productid name price description
1 beef steak 302 very tasty
2 apples 100 very tasty
3 chicken 250 very tasty
таблица productimages
imageid productid imagename
1 1 beefsteak1
2 1 beefsteak2
3 1 beefsteak3
4 2 apple1
5 2 apple2
6 2 apple3
поэтому у каждого продукта есть 3 изображения, которые хранятся в таблице productimages.
Теперь все, что я хочу, это получить мои данные в следующем формате: -
{
"productid": 1,
"name": "Beef steak",
"price": 302,
"description": "very tasty",
"imagename": ["beefsteak1","beefsteak2","beefsteak3"]
},
{
......
}
....
Я знаю, что мне нужно использовать внутреннее соединение, но я не очень хорошо разбираюсь в запросах и mysql, запрос, который я использую прямо сейчас:
select products.productid,products.name,products.price,products.description,imagename from products inner join productimages
on products.productid = productimages.productid;
, но это не работает должным образом.
nodejs
product.service. js
const con = require("../../config/database")
module.exports = {
getProducts : (callback) => {
const sql = "CALL p_getProduct()";
con.query(sql, (err, result) => {
if(err) {
return callback(err);
} return callback(null, result);
})
}
}
product.controller. js
const controller = require("./product.service");
module.exports = {
getProducts: (req, res) => {
controller.getProducts((err, result) => {
if(err) {
console.log(err);
return res.json({
success: 0,
message: "There is something wrong"
})
} else {
return res.json({
success: 1,
message: result
})
}
})
}
}
product.router.js
const route = require("./product.controller");
const router = require("express").Router();
router.get("/getProducts", route.getProducts)
module.exports = router;
Прямо сейчас я получаю этот ответ в почтальоне:
{
"success": 1,
"message": [
[
{
"productid": 1,
"name": "beef steak",
"price": 302,
"description": "Very tasty",
"imagename": "beefsteak1"
},
{
"productid": 1,
"name": "beef steak",
"price": 302,
"description": "Very tasty",
"imagename": "beefsteak2"
},
{
"productid": 1,
"name": "beef steak",
"price": 302,
"description": "Very tasty",
"imagename": "beefsteak3"
},
.....
, но я хочу вот так:
{
"success": 1,
"message": [
[
{
"productid": 1,
"name": "beef steak",
"price": 302,
"description": "Very tasty",
"imagename": ["beefsteak1","beefsteak2","beefsteak3"]
},
{
"productid": 2,
"name": "Apples",
"price": 100,
"description": "Do you really......",
"imagename": ["apple1","apple2","apple3"]
},
.....an so on.
Спасибо.