【发布时间】:2021-06-19 05:08:20
【问题描述】:
我是 node.js 的新手,我正在从数据库(操作)中获取一些数据。每个动作都在另一个表中注册了许多图像,以便我可以通过动作 id 获取它们。
我正在尝试将这些图像的数组添加到相应的操作中,以便我可以在前端循环它们。
在 php 中我经常这样做:
$return = array();
$images = array();
$image = array();
$select = "SELECT id, title, description FROM actions WHERE id = ? order by id DESC";
$stmt = $mysqli->prepare($select);
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $title, $description);
while ($stmt->fetch()) {
$registers = array(
"id" => $id, "title" => $title, "description" => $description, "images" => $image
);
$selectImages = mysqli_query($mysqli, "SELECT id, image FROM action_images WHERE action_id = '" . $id . "' ");
while ($row = $selectImages->fetch_array(MYSQLI_BOTH)) {
$images = array("imageID" => $row['id'], "image" => $row['image']);
array_push($registers["images"], $images);
}
$return[] = $registers;
}
在 javscript/node.js 中有类似的东西吗?我尝试了以下代码中描述的一些事情,但没有按预期工作。
这是我的控制器:
async selectActions(req, res) {
let actionData = [];
conn.execute('SELECT * FROM actions',
function (err, results, fields) {
// console.log(err);
// console.log(results);
if (err == null) {
results.forEach(action => {
conn.execute('SELECT * FROM actions_images WHERE actionID = ?',
[action.id],
function (imagesError, imagesResults, ImagesFields) {
// I've tried some things like:
actionData = [results, imagesResults];
// and
actionData = [...results, ...imagesResults]
// and
results.push(imagesResults)
// but nothing had the expected results displayed in the image below
console.log(actionData);
}
);
});
return res.json(results);
} else {
return res.json('error fetching actions from database: ' + err);
}
});
},
动作图像数组必须是每个动作项中的另一个项:
【问题讨论】:
标签: javascript node.js arrays reactjs