简体   繁体   中英

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

在此处输入图像描述

second table

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

在此处输入图像描述

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]);
    }

I fixed my problem by modifying my model

My model

    public function children()
    {
        return $this->hasMany(first_level::class, 'parent_id', 'Nominal')
            ->with('transactions')
            ->with('children')
            ->withsum('transactions', 'debit')
            ->withsum('transactions', 'credit');
    }

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

My Controller

        $items = first_level::with('children')
            ->where('parent_id', 0)
            ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM