0

Currently, I have 3 tables:

enter image description here

A customer can have a thousand invoices, and an invoice can have thousand of payments too.

My current query looks like this:

$invoices = DB::table('invoices')
        ->where('customer_id', $customer_id)
        ->get();

foreach ($invoices as $invoice) {
    // attach payments result to $invoice->all_payments
    $invoice->all_payments = DB::table('payments')
                                ->where('invoice_id', $invoice->id)
                                ->get();
}

My query works, though it takes a lot of time. I am looking for an alternative way to do this, performance wise.

My previous query using join:

    $data = DB::table('invoices')
                ->join('payments', 'invoices.id', '=', 'payments.invoice_id')
                ->where('customer_id', $customer_id)
                ->get();

Is there a better way of doing this?

halfer
  • 19,824
  • 17
  • 99
  • 186
wobsoriano
  • 12,348
  • 24
  • 92
  • 162

2 Answers2

0

You should try this:

 $data = DB::table('invoices')
                ->join('payments', 'invoices.id', '=', 'payments.invoice_id')
                ->leftJoin('customers', 'invoices.customer_id', '=', 'customers.id')
                ->where('customer_id', $customer_id)
                ->get();
0

How about using eloquent?

Invoice::with('payments')->where('customer_id', $customerId)->get();

You just need to add relationship method in your Invoice model like this:

public function payments()
{
    return $this->hasMany('App\Model\Payment');
}
azisuazusa
  • 317
  • 1
  • 12