laraveleloquent

Laravel Eloquent: aggregate for table


My tables (and Laravel models relations): projects -> tasks -> commands

Calculate count of tasks:

$body = Project->withCount('tasks')->get();

Fine.

Then I want to calculate count of commands for all tasks. SQL equivalent is:

select 
    count(commands.*)
from projects
inner join tasks on tasks.project_id = projects.id
inner join commands on commands.task_id = tasks.id

How to get it by Eloquent? For some reasons Query Builder is not acceptable.

Unfortunately, witchCount is not so flexible as with and I cannot use at as withCount('tasks.commands')


Solution

  • You can add the Task relationship to the Project model and the Command relationship through Task as well.

    class Project extends Model
    {
        function tasks()
        {
            return $this->hasMany('App\Task');
        }
    
        function commands()
        {
            return $this->hasManyThrough('App\Command', 'App\Task');
        }
    }
    

    After that, you can query both using withCount.

    Project::withCount(['tasks', 'commands']);