如何选择左连接表数据作为数组

时间:2016-04-15 12:12:19

标签: php mysql

我正在尝试在更新下方显示评论。请帮我知道如何从数据库中将所有注释作为数组。当我打电话给$ article->评论时,下面的代码只给我一个评论,如下所示,我只得到一个结果。对行进行计数会给出正确的计数,但显示只会产生一个结果。

$articlesQuery = $db->query("
SELECT 
updates.id, 
updates.update_text,
updates.posted_at,
updates.user_id,
updates.the_group,
members_comments.comment AS comments,

COUNT(articles_likes.id) AS likes,
GROUP_CONCAT(members.id SEPARATOR '|') AS liked_by

FROM updates


LEFT JOIN articles_likes
ON updates.id = articles_likes.article

LEFT JOIN members
ON articles_likes.user = members.id

RIGHT JOIN members_comments
ON members_comments.update_id = updates.id

GROUP BY updates.id

ORDER BY updates.id DESC

LIMIT 3
");

while ($row = $articlesQuery->fetch_object()){
$row->liked_by = $row->liked_by ? explode('|', $row->liked_by) : [];
$articles[] = $row;
}

然后显示,这会带来错误,但它解释了我想要做的事情。

foreach($articles as $article): 
echo $article->update_text; 

foreach ($article->comments as $comment){
                echo $article->comment;
}
endforeach;

1 个答案:

答案 0 :(得分:0)

我认为循环不正确。

Foreach $ article(现在是1行)

预告评论$ article echo comment

所以这个评论只会是1行的评论吗?

除非我误解了这应该是你的代码:

foreach($articles as $article) {
      print $article->update_text."\n";
      print $article->comment."\n";
}