Executing your counter caches - ml-archive/nodes-php-counter-cache GitHub Wiki
Now that you have implemented and defined your counter caches, all you need is now to specify when you want the counter caches to be executed.
A model supports five different types of events: created, updated, saved, deleted and restored. This packages comes with support for all of these events.
This package contains six traits:
- CounterCacheCreated - Executes the counter caches on the
createdevent - CounterCacheUpdated - Executes the counter caches on the
updatedevent. - CounterCacheSaved - Executes the counter caches on the
createdandupdatedevent. - CounterCacheDeleted - Executes the counter caches on the
deletedevent. - CounterCacheRestored - Executes the counter caches on the
restoredevent. - CounterCache - Executes the counter caches on
created,updated,deletedandrestoredevent.
By using traits it increases the flexible of "subscribing" to the model events. I.e. it would make it easy and quick to setup the counter caches to only execute when an entry has been created and restored after have being soft deleted.
To enable a specific event on your model, simply use the trait that on your model:
use Nodes\CounterCache\CounterCacheable;
use Nodes\CounterCache\Traits\CounterCacheCreated;
use Nodes\CounterCache\Traits\CounterCacheRestored;
class Post implements CounterCacheable
{
use CounterCacheCreated, CounterCacheRestored;
/**
* Post belongs to user
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
/**
* Retrieve array of counter caches.
*
* @return array
*/
public function counterCaches()
{
return [
'posts_count' => 'user'
];
}
}