'How to Get sum of transactions in Recursive query

I have two Tables, the first table have a parent-child relationship with itself, and the second table stores the transactions for the first table

First Table

Note: parent_id is in relationship with Nominal

enter image description here

second table

Note: first_level_id is in relationship with the id of the first table

enter image description here

in the model, I Created a relationship like below

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class first_level extends Model
{
    use HasFactory;
    use LogsActivity;


    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')->with(['children']);
    }

    public function transactions()
    {
        return $this->hasMany(second_level::class, 'first_level_id', 'id');
    }
}

Now in the controller when I want to get all the Children and their transactions I can only get the children without their transactions. So how do get all the children with the sum of their transactions?

My controller:

    public function getGeneralLedger(Request $request)
    {
     $items = first_level::with('children')->with('transactions')->where('parent_id', 0)->get();
     return response()->json(['data' => $items]);
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source