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

Feature request: TotalCache (similar to CountCache) #34

Closed cviebrock closed 8 years ago

cviebrock commented 8 years ago

In the same way we can add count caching to a model, it would be nice to have a behaviour that cached the sum of some value.

As an example, a User has many Orders. Right now, we could add a order_count field to the User model and use the existing behaviour to update that. I'm suggesting something that allows one to add a an order_total field as well, that is a cached copy of the sum of some field on the Orders table for that User. e.g.

UPDATE users SET order_total = (
  SELECT SUM(orders.amount) AS total FROM orders WHERE orders.user_id = users.id
) WHERE users.id = ?

Not sure how the configuration would look, but maybe something like this on the Order class:

public function totalCaches()
{
    // short syntax
    return [
        // class => fieldToSum
        User::class => 'amount'
    ];

    // full syntax
    return [
        // fieldName => [ class, foreignKey, key, fieldToSum ]
        'order_total' => [User::class, 'user_id', id', 'amount'],
    ];
}
kirkbushell commented 8 years ago

Yeah I've thought about that also, and it'll be a good feature (same with average). It fits well with the behaviours idea and system of Eloquence, so I'm happy to include something like this.

cviebrock commented 8 years ago

If you have a chance, can you take a look at the PR #35 I submitted? It's not passing the tests ... but I think that's because I have something set up incorrectly in the tests, not in the actual implementation.

Thanks!

kirkbushell commented 8 years ago

Will do @cviebrock - just been away on holidays (and currently sick).

cviebrock commented 8 years ago

Get well soon!

kirkbushell commented 8 years ago

I'll be renaming the SumCache to TotalCache - I think it's a better name :) Thanks for this.

cviebrock commented 8 years ago

Your package, so your call. :) I was trying to keep parity with the underlying SQL commands normally associated with the actions:

And thanks!

kirkbushell commented 8 years ago

hehe, I ended up reverting it back to sum anyway - Summable works nicely as a trait ^_^

cviebrock commented 8 years ago

Rolls off the tongue better than Totalable. ;)