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
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]);
}
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
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.