BelongsToMany CounterCache

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 and CounterCache and came up with this:



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


 $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!

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

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.