gabordemooij / redbean

ORM layer that creates models, config and database on the fly
https://www.redbeanphp.com
2.3k stars 279 forks source link

Request: Derived columns for lists #940

Open benmajor opened 4 months ago

benmajor commented 4 months ago

As far as I'm aware, there's currently no way of obtaining an aggregated column from a bean's own or shared list.

For example, if we have a Product bean which may have many Review beans in its ownReviewList, we sometimes need to get the average score for a given Product bean. When using Models, it would be super-handy to be able to use derived columns, similar to the with() or withCondition() methods. For example, the Product model may contain a method as follows (using psuedo-code for the missing RedBean functionality):

public function getAverageRating(): float
{
    return $this->bean->aggregate('AVG(score)')->ownReviewList;
}

Is this currently possible with RedBean (without computing the value manually using a loop of the ownReviewList), or do we have to use R::getCell() for the time-being? If it's the latter, it would be nice to implement this feature so that we don't need to taint models with calls to R-spaced methods.

Thanks! Ben.

gabordemooij commented 4 months ago

I always use R::cell for this. It's what SQL really shines at, making reports/aggregates etc.

gabordemooij commented 4 months ago

If you don't want to use static methods in your models, simply pass the adapter.