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(['' => '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) {
                                    'total_docs' => $q->func()->count('PostDocs.post_id')
                        return $q;
1 Like