Using CounterCache through a hasMany -> hasMany association

My current model:

  • A record belongsTo a city
  • A city belongsTo a country

Currently I’m storing how many records each city has with this simple config on RecordsTable.php:

$this->addBehavior(‘CounterCache’, [
‘Cities’ => [‘cantidad_registros’],
]);

Now, I want to also keep in the field Countries->records how many records does that country has.

https://book.cakephp.org/4/en/orm/behaviors/counter-cache.html
https://book.cakephp.org/4/en/orm/associations.html#hasmany-associations

I can’t find the solution on the book, I’ve also tried (without success) using a BelongsToMany even though I know this is not the case. I’m starting to think this is not possible to do using the CounterCache and I need to write my own code.

Thanks in advance!

if there is no country_id field on your records, it is not possible using the basic version.

1 Like

Thanks! that’s what I thought. I’ll write one myself.