简体   繁体   中英

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.

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?! The second inside sql would be:

$sql = "SELECT * FROM fb_clubnews WHERE ori_newsid = $storId ORDER BY newsid DESC";

How do I get the $commentArray filled up with comments.

My DB Structure for fb_clubnews looks like this:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM