/eloquent-aggregate-relationships

Allows for easily creating aggregate relationships that can be eager-loaded.

Primary LanguagePHP

Eloquent Aggregate Relationships

Work-in-progress

This laravel package provides tools for easily creating aggregate relationships that can be eager-loaded.

The primary issue is that eloquent out of the box won't let you eager-load and count a relationship without loading all of actual records of that relationship.

Proposed syntax

public function commentsCount() {
    return $this->countHasMany('Comment','post_id','comments_count');
}
$this->averageHasMany(...
$this->sumHasMany(...

etc


Project Inspiration

This project was inspired by the blog post Tweaking Eloquent relations – how to get hasMany relation count efficiently? by Jarek Tkaczyk (@SOFTonSOFA).

The post provided a solution for counting a relationship effeciently with the following syntax:

public function commentsCount()
{
  return $this->hasOne('Comment')
    ->selectRaw('post_id, count(*) as aggregate')
    ->groupBy('post_id');
}