How to get how much record in Associated Table

$this->UserPosts->hasMany(‘PostImages’, [‘className’ => ‘PostImages’, ‘foreignKey’ => ‘post_id’]);

    $this->UserPosts->hasMany('PostDocs', ['className' => 'PostDocs', 'foreignKey' => 'post_id']);

    $all_posts = $this->UserPosts->find('all')->where(['UserPosts.user_id IN' => $all_related_user])->contain(['PostImages', 'PostDocs'=> ['fields' => ['total_docs'=>'COUNT(name)']]])->order(['UserPosts.id' => 'DESC']);

Want to get only count how much rows inside ‘PostDocs’ table related to ‘UserPosts’. Want outoput like ‘total_docs’ as a array element.

Don’t want to retrive all records ‘PostDocs’ and then use array count, like count(all_posts[‘post_doc’]) .

Finally got solution

'PostDocs'=> function($q) {
                        $q->select([
                                    'PostDocs.post_id',
                                    'total_docs' => $q->func()->count('PostDocs.post_id')
                                ])
                                ->group(['PostDocs.post_id']);
                        return $q;
                    }
1 Like

Read https://book.cakephp.org/4/en/orm/behaviors/counter-cache.html