kirkbushell / eloquence

A drop-in library for certain database functionality in Laravel, that allows for extra features that may never make it into the main project.
MIT License
537 stars 58 forks source link

Cache count clarification #31

Closed cviebrock closed 8 years ago

cviebrock commented 8 years ago

I have a Category model that has many Services. My categories table has columns for _categoryid (the primary key) and _servicescount, among other fields. The services table has _serviceid (primary key) and _categoryid, among others.

My Service model looks something like:

class Service extends Model implements CountCache
{
    use CamelCaseModel;

    protected $primaryKey = 'service_id';

    ...

    public function countCaches()
    {
        return [
            'services_count' => [Category::class, 'category_id', 'category_id'],
        ];
    }
}

Finally, in App/Providers/AppServiceProvider.php, I have in my register() method:

class AppServiceProvider extends ServiceProvider
{

    ...

    public function register()
    {
        Service::observe(new CountCacheObserver());
    }
}

When I create a new Service model, or edit an existing on, the _servicescount field on the corresponding Category model isn't increasing. Where did I goof?

cviebrock commented 8 years ago

Figured it out ... the line Service::observe(new CountCacheObserver()); needs to go in the boot() method of the AppServiceProvider, not the register() method.

I'll send a PR to update the docs to clarify that, if you don't mind.