Search code examples
doctrinedql

count number of foreign key in doctrine


This is follow up of this question: count number of foreign keys

I am using doctrine 1.2 and I want to count the number of business that belongs to subcategory.

Following are the mysql tables.

1.fi_category

+----+-----------------+-----------------+
| id | name            | slug            |
+----+-----------------+-----------------+

2.fi_subcategory

+----+-----------------+-----------------+-------------+
| id | name            | slug            | category_id |
+----+-----------------+-----------------+-------------+

3.fi_business_subcategory

+----+-------------+----------------+
| id | business_id | subcategory_id |
+----+-------------+----------------+

I am using this DQL.

$q = Doctrine_Query::create()
    ->select('c.name, c.slug, sc.name, sc.slug')
    ->from('Model_Category c')
    ->leftJoin('c.Subcategory sc')
    ->leftJoin('sc.BusinessSubcategory bsc');

which gives me something like this.

Array
(
    [0] => Array
    (
        [id] => 1
        [name] => Entertainment & Lifestyle
        [slug] => entertainment-lifestyle
        [Subcategory] => Array
        (
            [0] => Array
            (
                [id] => 1
                [name] => Arts and Crafts
                [slug] => arts-and-crafts
            )
            [1] => Array
            (
                [id] => 2
                [name] => Family
                [slug] => family
            )
            [2] => Array
            (
                [id] => 3
                [name] => Fashion
                [slug] => fashion
            )
        )
    )
)

I am looking to fetch the number of business, i.e the returned result should be something like this depending on the business it belongs.

Array
(
    [0] => Array
    (
        [id] => 1
        [name] => Entertainment & Lifestyle
        [slug] => entertainment-lifestyle
        [Subcategory] => Array
        (
            [0] => Array
            (
                [id] => 1
                [name] => Arts and Crafts
                [slug] => arts-and-crafts
                [business_count] => 35
            )
            [1] => Array
            (
                [id] => 2
                [name] => Family
                [slug] => family
                [business_count] => 10
            )
            [2] => Array
            (
                [id] => 3
                [name] => Fashion
                [slug] => fashion
                [business_count] => 27
            )
        )
    )
)

Tried various ways using DQL, but nothing seems to work out. Any idea how should I go with what I want?


Solution

  • Did you try:

    $q = Doctrine_Query::create()
         ->select('c.name, c.slug, sc.name, sc.slug, COUNT(sc.BusinessSubcategory.id) AS business_count')
         ->from('Model_Category c')
         ->leftJoin('c.Subcategory sc')
         ->groupBy('c.id, sc.id');
    

    with HYDRATE_ARRAY