从 Propel ORM 中的第二个 table 开始获取行数

Get row count from second table in Propel ORM

我对 Propel ORM 有点陌生,我使用的版本有点旧 (1.x)。我正在开发的应用程序无法以任何方式更新。我有以下架构:

<table name="blog">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="title" type="varchar" size="100" required="true" />
    <column name="user_id" type="integer" required="false" />
    <column name="author" type="varchar" size="100" required="true" default="Anonimous" />
    <column name="body" type="longvarchar" required="true" />
    <column name="publish_date" type="timestamp" required="true" />
    <behavior name="timestampable" />
    <behavior name="soft_delete" />
    <behavior name="sluggable">
        <parameter name="slug_pattern" value="{Title}" />
        <parameter name="replace_pattern" value="/[^\w]+/u" />
        <parameter name="replacement" value="-" />
        <parameter name="separator" value="-" />
        <parameter name="permanent" value="true" />
    </behavior>

    <foreign-key foreignTable="user">
        <reference local="user_id" foreign="id"/>
    </foreign-key>

</table>

<table name="comment">
    <column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
    <column name="blog_id" type="integer" required="true" />
    <column name="user_id" type="integer" required="false" default="-1" />
    <column name="author" type="varchar" required="false" default="Anonimous" />
    <column name="body" type="longvarchar" required="true" />

    <foreign-key foreignTable="user">
        <reference local="user_id" foreign="id"/>
    </foreign-key>

    <foreign-key foreignTable="blog">
        <reference local="blog_id" foreign="id"/>
    </foreign-key>

    <behavior name="timestampable" />
    <behavior name="soft_delete" />
</table>

我需要通过查询博客 table 来获取 "each" 博客条目的评论数。

这是我的控制器查询:

$posts = BlogQuery::create()
        ->orderByPublishDate('desc')
        ->filterBy('PublishDate', time(), "<")
        ->paginate($page, $maxPerPage);

我需要向每条记录添加属于该特定记录的评论计数,该计数基于架构中所述的blog_id

<foreign-key foreignTable="blog">
    <reference local="blog_id" foreign="id"/>
</foreign-key>

谁能帮帮我?

我从评论对话中得到了答案:

A simple solution is just to use $posts[0]->countComments(), which will issue a separate COUNT(*) query for the appropriate Blog row's related records.

->countComments() 使用 Twig 成功了。这将打印每个博客的评论 post:

Comments: {{post.countComments()}}

您可以使用以下代码

BlogQuery::create('blog')
    ->leftJoinComment('comment')
    ->withColumn('COUNT(comment.id)', 'CommentCount')
    ->groupById()
    ->paginate($page, $maxPerPage);

现在您可以使用 $blog->getCommentCount()