簡體   English   中英

使用參數 Laravel 急切加載

[英]Eager loading with parameter Laravel

我想要做的是使用 $date 參數從分類帳表中獲取所有具有額外價值的科目表,即余額,是否有任何適當的方法可以做到這一點,因為我在這里面臨 N+1 查詢問題。

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

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. 建立COALedger的關系

正品證書COA

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

Ledger Model

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM