# How to get how much record in Associated Table

**URL:** https://discourse.cakephp.org/t/how-to-get-how-much-record-in-associated-table/8644
**Category:** Need Help
**Tags:** behavior
**Created:** [November 21, 2020, 9:54am UTC](https://discourse.cakephp.org/t/how-to-get-how-much-record-in-associated-table/8644 "2020-11-21T09:54:40Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![debendra986](https://avatars.discourse-cdn.com/v4/letter/d/c5a1d2/32.png) [@debendra986](https://discourse.cakephp.org/u/debendra986)
#### Post date: [November 21, 2020, 9:54am UTC](https://discourse.cakephp.org/t/how-to-get-how-much-record-in-associated-table/8644/1 "2020-11-21T09:54:41Z")

</div>

> $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’]) .

---

<div class="post-metadata">

### Author: ![debendra986](https://avatars.discourse-cdn.com/v4/letter/d/c5a1d2/32.png) [@debendra986](https://discourse.cakephp.org/u/debendra986)
#### Post date: [November 23, 2020, 7:12am UTC](https://discourse.cakephp.org/t/how-to-get-how-much-record-in-associated-table/8644/2 "2020-11-23T07:12:46Z")

</div>

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;
                    }
```

---

<div class="post-metadata">

### Author: ![Salines](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/salines/32/3166_2.png) [@Salines](https://discourse.cakephp.org/u/Salines)
#### Post date: [November 23, 2020, 10:28am UTC](https://discourse.cakephp.org/t/how-to-get-how-much-record-in-associated-table/8644/3 "2020-11-23T10:28:46Z")

</div>

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