Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count in contain Cakephp 3

I have a table Post and this has a has-many association with a table Stars.

I can get all the associated data using:

$this->Posts->find()->contain(['Stars']);

That works well.

But I want to count the Stars. I have tried this but its not working:

$this->Posts->find->contain([
    'Stars' => function($q) {
        return $q->select(['total' => $q->func()->count('Stars.post_id')]);
    }
]);

//I've also tried this
...
...$q->select(['total' => "COUNT(Stars.post_id)"]);
...
//Also fail

This does not return the number of associated Stars.

Is there something wrong or should do it some other way?

Thanks

like image 577
Willian Avatar asked Apr 26 '16 23:04

Willian


People also ask

What is contain in CakePHP?

A new addition to the CakePHP 1.2 core is the ContainableBehavior . This model behavior allows you to filter and limit model find operations. Using Containable will help you cut down on needless wear and tear on your database, increasing the speed and overall performance of your application.

How can I get data from database in CakePHP?

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.

How can I order in CakePHP?

To apply ordering, you can use the order method: $query = $articles->find() ->order(['title' => 'ASC', 'id' => 'ASC']);


1 Answers

you have to select also the foreign key otherwise cake is not able to join the tables. And you have also to group the result

'Stars' => function($q) {
    $q->select([
         'Stars.post_id',
         'total' => $q->func()->count('Stars.post_id')
    ])
    ->group(['Stars.post_id']);

    return $q;
}
like image 72
arilia Avatar answered Oct 23 '22 05:10

arilia