Search code examples
phpsymfonypropel

Get row count from second table in Propel ORM


I'm somewhat new to Propel ORM, and the version I'm using is somewhat old (1.x). The app I'm working on cannot by any means be updated. I have the following schema:

<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>

I need to get by querying the blog table, the comment count for "each" blog entry.

here is my controller query:

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

I need to add to each record, a count of the comments that belong to that particular record based on the blog_id as stated on the schema

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

Any one can give me a hand?


Solution

  • I got an answer from a comments conversation:

    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.

    The ->countComments() did the trick, using Twig. This prints the comments for each blog post:

    Comments: {{post.countComments()}}