【发布时间】:2009-08-03 13:06:42
【问题描述】:
我想在包含博客文章列表的页面上显示每篇博客文章的 cmets 数量(以及类别、日期、作者等)。我如何在propel中编写以下mysql查询?
SELECT post.id, post.title, post.more_columns , COUNT(comments.post_id) AS numofcomments FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id, post.title, post.more_columns
其中 post 是一个 blog 表和 cmets,一个 cmets 表,其中 post_id 作为 post.id 的外键。我似乎无法将“numofcmets”作为结果集中的一列。目前我正在使用非 ORM 方法(这将是我最后的手段):
$con = Propel::getConnection(PostPeer::DATABASE_NAME);
$sql = "SELECT post.* , COUNT(comments.post_id) AS numcomments FROM post INNER JOIN comments ON post.id = comments.post_id GROUP BY post.id";
$stmt = $con->prepare($sql);
$stmt->execute();
$result = PostPeer::populateObjects($stmt);
return $result;
如何在生成的 Propel 结果集中访问“numofcmets”?
编辑:我想知道如何在 Propel 中编写上述查询?我现在可以做的是在 cmets 表上获取带有内部连接的 post 表,然后在 cmets 表上为每个 post-id 运行 doCount。这导致对 Post 表的 1 个查询和对 cmets 表的许多查询。我希望将 sql 查询减少到最低限度。 谢谢:)
【问题讨论】: