PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 22, 2022

[FIXED] How to Get sum of transactions in Recursive query

 February 22, 2022     eloquent, laravel, mysql, php     No comments   

Issue

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

Solution

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();


Answered By - eraufi
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing