简体   繁体   中英

fetch record from with dependent relations in laravel

I have the following tables.

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. I want to get all the users which have full paid total amount of the diploma invoice.
  2. I want also get all the users which have not full paid total amount of the diploma invoice.

I'm currently looping through the each relation.

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

then foreach loop on users and get all invoices.

$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'){

        }

But I'm still unable to find actual records.

your question is different and your code is different.

if you want relation data then you can fetch relation data using "With" and if you want less_paid | no_paid then you can use where statement in your relation model function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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