Total number of linked models

Hi,

I have two models with a simple 1-n relation (category and item with category_id). I would like to show how much items there is in the category. I would like to have the number cached rather then always doing the count, so I have an extra field in category table called "total_items_count".

How to best do this total count triggering, when to call the "countUpdate" function since the relation could change from several places (backend, api, frontend…).

My initial plan was to use AFTER_UPDATE event, but “link()” must be called after the item is stored in database (on adding new item at least) so then I do not know which category is the item related to. I also need to know the old category, in case item goes from one category to another. In the backend controller I am using $item->link(‘category’, $categoryObj); as I might change this relation to n-n someday.

Any advice on how to have complete control if the link between item and category changes and then update the count for the old and new linked category?

Thanks

Hi dajo,

Probably I would not try to cache the item count in the database table. It looks expensive and error-prone.

I would consider using query cache (or data cache in general), fragment cache and/or page cache instead.

If I do have to keep track of the count in the table, I would consider using trigger in the database layer.

I would like to hear the opinions of other people. :)