[英]Get story and all its comments in 1 query
I am trying to create an PHP api in which I am trying to retrieve news storys and all its comments and send it as json. 我正在尝试创建一个PHP API,在其中我试图检索新闻报道及其所有注释并将其作为json发送。
Here is what i have so far: 这是我到目前为止所拥有的:
$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);
}
}
My issue is, that I would like to avoid creating a sql inside an sql and loop through it?! 我的问题是,我想避免在sql中创建sql并循环遍历它? The second inside sql would be: 里面的第二个sql是:
$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";
How do I get the $commentArray filled up with comments. 如何使$ commentArray充满注释。
My DB Structure for fb_clubnews looks like this: 我的fb_clubnews数据库结构如下所示:
int newsid (autoincrement),
int userid,
text news,
int data,
int time,
int matchid,
int ori_newsid
Hoping for help on this and thanks in advance :-) 希望对此有所帮助,并预先感谢:-)
Something like this: 像这样:
$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.