# BelongsToMany CounterCache

**URL:** <https://discourse.cakephp.org/t/belongstomany-countercache/10768>\
**Category:** Uncategorized\
**Created:** [November 17, 2022, 5:15pm UTC](https://discourse.cakephp.org/t/belongstomany-countercache/10768 "2022-11-17T17:15:04Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mvojwe](https://avatars.discourse-cdn.com/v4/letter/m/9d8465/32.png) [@mvojwe](https://discourse.cakephp.org/u/mvojwe)\
**Post date:** [November 17, 2022, 5:15pm UTC](https://discourse.cakephp.org/t/belongstomany-countercache/10768/1 "2022-11-17T17:15:04Z")

</div>

I have 4 tables:

- **animals** : id
- **animals\_places** : animal\_id, place\_id, from, to
- **places** : id
- **unloads** : place\_id, timestamp, quantity\_of\_animals

My goal is to keep track, for each unload, of how many animals were in that place at that moment.

I’ve read [BelongsToMany associations](https://book.cakephp.org/4/en/orm/associations.html#belongstomany-associations) and [CounterCache](https://book.cakephp.org/4/en/orm/behaviors/counter-cache.html#belongs-to-many-usage) and came up with this:

**AnimalsPlacesTable.php**

```auto
$this->belongsToMany('Unloads')
   ->setThrough('Places')
   ->setBindingKey('place_id')
   ->setForeignKey('id')
   ->setTargetForeignKey('id');

 $this->addBehavior('CounterCache', [
    'Unloads' => ['quantity_of_animals'],
 ]);

```

**Test.php**

```auto
 $unload = $this->Unloads->newEntity([
    'place_id' => 1,
    'timestamp' => FrozenTime::now(),,
    'quantity_of_animals' => 0
 ]);

 $animalplace = $this->AnimalsPlaces->newEntity([
    'place_id' => 1,         
    'animal_id' => 1,
    'from' => FrozenTime::now()->subYears(300),
    'to' => FrozenTime::now()->addYears(300);
 ]);

```

After I add both entities, I check my database and the quantity\_of\_animals is still 0.

What am I doing wrong? Thanks in advance!

---

<div class="post-metadata">

**Author:** ![KevinPfeifer](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/kevinpfeifer/32/3365_2.png) [@KevinPfeifer](https://discourse.cakephp.org/u/KevinPfeifer)\
**Post date:** [November 18, 2022, 11:26am UTC](https://discourse.cakephp.org/t/belongstomany-countercache/10768/2 "2022-11-18T11:26:11Z")

</div>

Your DB schema is not very clear to me.  
A typicall belongsToMany has 3 tables but you have 4.

Can you draw an ER diagramm to better explain how your tables are related to each outer.

Regarding the CounterCache behavior inside a belongsToMany:  
It is placed on the table instance which represents the junction table, so the one which contains the `belongsTo` associations. See the yellow banner above [CounterCache - 4.x](https://book.cakephp.org/4/en/orm/behaviors/counter-cache.html#belongs-to-many-usage)

So depending on where you have your `belongsTo` associations you have to put the behavior on that specific table class to enable the CounterCache behavior.
