Search code examples
phplaraveleloquentlumen

Lumen/Laravel: sum on nested relationships


i've got these nested relationship in Lumen 8, i'm looking for a well-done Eloquent way to show the sum of files size, but on relation father level. That's my situation:

Procedures ->(hasMany) Documents ->(hasMany) DocumentFiles

I want to sum DocumentFiles->size but on Procedure. (field procedure_files_size) If possible i would like to show the sum also for the single document. (field document_files_size)

That's like what i'm expecting to have when returning the Procedure Object:

{
    "id": 1,
    "title": "Exercitationem ea distinctio consectetur.",
    "description": "Deserunt perferendis impedit laboriosam nemo hic unde est et. Quia dolores tempora incidunt iste dolor fugiat harum quae. Ducimus sit quo ut recusandae rerum qui.",
    "expiry": "2021-05-31 04:51:15",
    "status": "hidden",
    "created_at": "2021-05-27T13:47:32.000000Z",
    "updated_at": "2021-05-27T13:47:32.000000Z",
    "users_count": 2,
    "documents_count": 5,
    "procedure_files_size": 1240000
    "users": [
        {
            "id": 1,
            "email": "[email protected]",
            "name": "name",
            "surname": "surname",
        }
    ],
    "documents": [
        {
            "id": 1,
            "procedure_id": 1,
            "title": "docname",
            "description": "Lorem ipsum ",
            "priority": "standard",
            "created_at": "2021-05-27T13:49:31.000000Z",
            "updated_at": "2021-05-27T13:49:31.000000Z",
            "document_files_size": 1240000,
            "document_files": [
                {
                    "id": 1,
                    "document_id": 1,
                    "path": "path_to_file",
                    "extension": null,
                    "size": 34020,
                    "created_at": "2021-05-27T13:51:25.000000Z",
                    "updated_at": "2021-05-27T13:51:25.000000Z"
                }
            ]
        }
    ]
}

I tried something like that but didn't work:

Procedure::with(['users','documents.documentFiles'])->withCount('users')->withSum('documents.documentFiles','size'))->find(1);

Thanks!!


Solution

  • On your Procedure model, as documentFiles as a hasManyThrough relation.

    class Procedure {
        public function documentFiles() {
            return $this->hasManyThrough(DocumentFile::class, Document::class);
        }
    }
    

    Now you should be able to use withSum() on that relation.

    ->withSum('documentFiles','size'))