簡體   English   中英

從 laravel 中獲取依賴關系的記錄

[英]fetch record from with dependent relations in laravel

我有下表。

users -> id, name, email, password
diplomas -> id, name
user_diploma -> user_id, diploma_id
invoices -> id, user_id, total_amount
invoice_items -> id, item_id, item_type // items can be diplomas or any other models also.
payments -> id, invoice_id, paid_amount
  1. 我想獲得所有已全額支付文憑發票總額的用戶。
  2. 我還想獲得所有未全額支付文憑發票總額的用戶。

我目前正在遍歷每個關系。

$users = User::has('diplomas');

然后對用戶進行 foreach 循環並獲取所有發票。

$users = User::has('diplomas');
        if($this->paymentStatus == 'full_paid'){
            foreach ($users as $user) {
                $diplomas = $user->diplomas->pluck('id')->toArray();
                $invoices = $user->invoices()
                                 ->whereHas('items', function ($q) use ($diplomas) {
                                    $q->whereItemType(\App\Models\Diploma::class);
                                    $q->whereIn('item_id', $diplomas);
                                })
                                ->whereHas('payments', function ($q){
                                    // still don't know how to fetch the invoice id here to compare the total paid amount
                                })->get();
                $allInvoices = $allInvoices->merge($invoices);
            }
        }
        else if($this->paymentStatus == 'less_paid'){

        }
        else if($this->paymentStatus == 'no_paid'){

        }

但我仍然無法找到實際記錄。

您的問題不同,您的代碼也不同。

如果你想要關系數據,那么你可以使用“With”獲取關系數據,如果你想要 less_paid | no_paid 那么你可以在你的關系 model function 中使用 where 語句。

暫無
暫無

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

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