如何在递归查询中获取交易总和
How to Get sum of transactions in Recursive query
我有两个 Table,第一个 table 与自身有 parent-child 关系,第二个 table 存储第一个 [=40] 的交易=]
第一个Table
注:parent_id与Nominal
有关系
秒table
注:first_level_id与第一个id有关table
在模型中,我创建了如下关系
<?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');
}
}
现在在控制器中,当我想获得所有 Children 及其交易时,我只能获得没有交易的 children。那么如何用他们的交易总和得到所有的children呢?
我的控制器:
public function getGeneralLedger(Request $request)
{
$items = first_level::with('children')->with('transactions')->where('parent_id', 0)->get();
return response()->json(['data' => $items]);
}
我通过修改我的模型解决了我的问题
我的模型
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');
}
我的控制器
$items = first_level::with('children')
->where('parent_id', 0)
->get();
我有两个 Table,第一个 table 与自身有 parent-child 关系,第二个 table 存储第一个 [=40] 的交易=]
第一个Table
注:parent_id与Nominal
有关系秒table
注:first_level_id与第一个id有关table
在模型中,我创建了如下关系
<?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');
}
}
现在在控制器中,当我想获得所有 Children 及其交易时,我只能获得没有交易的 children。那么如何用他们的交易总和得到所有的children呢?
我的控制器:
public function getGeneralLedger(Request $request)
{
$items = first_level::with('children')->with('transactions')->where('parent_id', 0)->get();
return response()->json(['data' => $items]);
}
我通过修改我的模型解决了我的问题
我的模型
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');
}
我的控制器
$items = first_level::with('children')
->where('parent_id', 0)
->get();