简体   繁体   English

使用参数 Laravel 急切加载

[英]Eager loading with parameter Laravel

What I want to do is to get all charts of accounts with extra value ie balance from the ledgers table with the parameter of $date, Is there any proper way to do it because I am facing N+1 query problem here.我想要做的是使用 $date 参数从分类帐表中获取所有具有额外价值的科目表,即余额,是否有任何适当的方法可以做到这一点,因为我在这里面临 N+1 查询问题。

Controller Controller

public function get(Request $request){

    $date = $request->date;

    $coas = COA::where('parent_id', null)->get();
    //return $coas;

    $coas = $coas->map(function ($coa) use ($date) {
        $coa['balance'] = $coa->balance($date);
        return $coa;
    });
    return view('website.accounts.Trial.show', compact('coas', 'date'));
}

Model Model

public function balance($date){
        $date = new Carbon($date);
        $date= $date->addHours(23)->addMinutes(59)->addSeconds(59);
        $balance = Ledger::where('c_o_a_id', $this->id)
            ->where('created_at' ,'<=', $date)
            ->orderBy('created_at', 'desc')
            ->orderBy('id', 'desc')
            ->pluck('balance')
            ->first();

        if($balance){
            return $balance;
        }
        return 0;
    }

1. Set up a relationship between COA and Ledger 1. 建立COALedger的关系

COA Model正品证书COA

public function ledgers()
{
    return $this->hasMany(Ledger::class, 'c_o_a_id');
}

Ledger Model Ledger Model

public function coa()
{
    return $this->belongsTo(COA::class, 'c_o_a_id');
}

2. Make you balance() function use that relationship to avoid querying N+1 times 2.让你balance() function 使用那个关系来避免查询N+1次

COA Model

public function balance($date){
    $date = new Carbon($date);
    $date = $date->addHours(23)->addMinutes(59)->addSeconds(59);

    if (!$this->relationLoaded('ledgers') $this->load('ledgers');

    $balance = $this->ledgers->where('created_at' ,'<=', $date)
        ->sort(function ($a, $b) {
            return [$b->created_at, $b->id] <=> [$a->created_at, $a->id];
        })
        ->first()
        ->balance;
    
    return $balance ?: 0;
}

Controller Controller

    $coas = COA::with('ledgers')->where('parent_id', null)->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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