Laravel中Eloquent关联下groupBy查询发票详情的问题求助
Hey there! Let's break down why those extra invoice lines aren't showing up and how to fix it.
The Root Problem
Your current query uses groupBy('invoice_no') at the SQL level—but SQL's GROUP BY is meant for aggregating data (like counting rows or summing values), not grouping full records. When you use it here, it collapses all rows with the same invoice_no into a single row, which is why you're losing all those additional lines you need.
The Solution: Group at the Collection Level Instead
Instead of grouping in your database query, fetch all the relevant records first, then group them using Laravel's Collection methods. This keeps every full row intact while organizing them by invoice number.
Here's the updated controller code:
public function orderProformaInvoiceDetails($poi) { // Fetch all matching records with their related models $allInvoiceRecords = OrderProformaInvoice::where('opi_id', $poi) ->with('buyer', 'buyerJobs', 'buyerOrders') ->orderBy('created_at', 'DESC') ->get(); // Group the collection by invoice_no to keep all lines per invoice $orderProformaInvoiceDetails = $allInvoiceRecords->groupBy('invoice_no'); return view('admin.marchendaising.order-proforma-invoices.details', compact('orderProformaInvoiceDetails')); }
How to Display This in Your View
Now in your Blade template, you can loop through each invoice group to show the header info (using the first line's related data, assuming all lines under an invoice share the same buyer/order details) and then iterate through every line item:
@foreach($orderProformaInvoiceDetails as $invoiceNumber => $invoiceLines) <div class="invoice-container"> <!-- Invoice Header --> <h2>Invoice #{{ $invoiceNumber }}</h2> <div class="invoice-meta"> <p>Buyer: {{ $invoiceLines->first()->buyer->name }}</p> <p>Job: {{ $invoiceLines->first()->buyerJobs->title }}</p> <p>Order: {{ $invoiceLines->first()->buyerOrders->order_number }}</p> </div> <!-- Invoice Line Items --> <table class="invoice-lines"> <thead> <tr> <th>Item Name</th> <th>Quantity</th> <th>Unit Price</th> <th>Total</th> </tr> </thead> <tbody> @foreach($invoiceLines as $line) <tr> <td>{{ $line->item_name }}</td> <td>{{ $line->quantity }}</td> <td>{{ $line->unit_price }}</td> <td>{{ $line->quantity * $line->unit_price }}</td> </tr> @endforeach </tbody> </table> </div> @endforeach
Quick Notes
- If for some reason lines under the same invoice have different buyer/order data, you'll need to adjust your data structure or logic—but based on your "creation time" expected layout, this should work perfectly.
- Using Laravel's Collection
groupBykeeps all your raw record data intact, so you can access every field from each line item without losing anything.
内容的提问来源于stack exchange,提问作者Rashed Hasan

