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

CountCache for multiple models with same column name #36

Closed cviebrock closed 8 years ago

cviebrock commented 8 years ago

I have User, Category and Service models. A Service belongs to a category, and Users have many Services. The primary keys on the models are user_id, category_id and service_id respectively. The join keys are the same (i.e. service.user_id and service.category_id).

I want to create cache count for both the number of services per category, and the number of services per user. I can't do this in my Service class:

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

Because the column names are the same (category.services_count and user.services_count), I can't key my array using the same column name.

Am I missing something?

kirkbushell commented 8 years ago

Ah, I haven't encountered that use-case before. It would seem it's simply not possible. In that case, a change needs to be made so that the services_count could be a multi-dimensional array?

cviebrock commented 8 years ago

Or, the "long" form syntax needs to be more explicit. For example, the short form:

return [
   Category::class,
   User::class
];

And the proposed long form:

return [
    [Category::class, 'services_count', 'category_id', 'category_id'],
    [User::class, 'services_count', 'user_id', 'user_id'],
];

Or (my preference), even more verbose but very explicit:

return [
    [
        'model'      => Category::class,
        'countField' => 'services_count',
        'foreignKey' => 'category_id',
        'key'        => 'category_id',
    ],
    [
        'model'      => User::class,
        'countField' => 'services_count',
        'foreignKey' => 'user_id',
        'key'        => 'user_id',
    ],
];
cviebrock commented 8 years ago

Well, I guess I'm super productive when I wake up early. #37 adds this ability while maintaining backwards compatibility.

kirkbushell commented 8 years ago

Ah, that answers the question i had on the PR then. I'll merge in :) Thanks!