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:
AnimalsPlacesTable.php
$this->belongsToMany('Unloads')
->setThrough('Places')
->setBindingKey('place_id')
->setForeignKey('id')
->setTargetForeignKey('id');
$this->addBehavior('CounterCache', [
'Unloads' => ['quantity_of_animals'],
]);
Test.php
$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!