[英]Get story and all its comments in 1 query
我正在嘗試創建一個PHP API,在其中我試圖檢索新聞報道及其所有注釋並將其作為json發送。
這是我到目前為止所擁有的:
$sql = "SELECT * FROM fb_clubnews WHERE clubid='$groupId' AND ori_newsid = 0 ORDER BY newsid DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["newsid"];
$commentArray = array();
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}
我的問題是,我想避免在sql中創建sql並循環遍歷它? 里面的第二個sql是:
$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";
如何使$ commentArray充滿注釋。
我的fb_clubnews數據庫結構如下所示:
int newsid (autoincrement),
int userid,
text news,
int data,
int time,
int matchid,
int ori_newsid
希望對此有所幫助,並預先感謝:-)
像這樣:
$sql = "SELECT *, A.newsid as main_news_id FROM fb_clubnews A LEFT JOIN fb_clubnews B ON B.ori_newsid = A.newsid WHERE A.clubid='$groupId' AND A.ori_newsid = 0 ORDER BY A.newsid DESC";
$result = $conn->query($sql);
$wallAray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$storId = $row["main_news_id"];
if(array_key_exists($storId, $wallAray)) {
$commentArray[] = $wallAray;
} else {
$wallAray[$storId] = array();
$commentArray = array();
}
$wallAray[] = array("author"=>$row["userid"],
"story"=>$row["news"],
"date"=>$row["date"],
"time"=>$row["time"],
"matchid"=>$row["fk_match_id"],
"comments"=>$commentsArray);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.