Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Combining paginate and joined table #153

Open
mwebsites94 opened this issue Apr 14, 2020 · 1 comment
Open

Combining paginate and joined table #153

mwebsites94 opened this issue Apr 14, 2020 · 1 comment

Comments

@mwebsites94
Copy link

mwebsites94 commented Apr 14, 2020

Hello everybody

I have an invoice model which is related to another model (addresses) in which the address and name of the person the invoice is sent to are stated. I create an overview and want to sort by a couple of things, such as date, invoice number and name of the addressed person. The relation is defined trough a hasOne function.

I have tried two solutions in which different problems occur

option 1 invoicecontroller.php:

$invoices = Auth::user()->invoice()->with(['address'])
->join('addresses', 'invoices.id', '=', 'addresses.invoice_id')
->sortable()
->paginate(25);

return view('admin.invoices.overview', compact('invoices'));

In this everyhting except the sorting by name. This does nothing.

Another option is this:

invoicecontroller.php

$invoices = Auth::user()->invoice()->sortable(['invoice_date' => 'desc'])->paginate(25);
return view('admin.invoices.overview', compact('invoices'));

Invoice.php

public function nameSortable($query, $direction){
  return $query->join('addresses', 'invoices.id', '=', 'addresses.invoice_id')
  ->orderBy('name', $direction);
}

In this I can sort by anything but it doesnt show the name. When I sort by name the names show up again. A workaround is to print the name differently, namely $invoice->address->name instead of $invoice->name, but than I can't sort by name anymore.

Does anybody know a workaround?

@Kyslik
Copy link
Owner

Kyslik commented Apr 20, 2020

This looks like an edge case I did not think about :(.

Can you post SQLs for both cases? You can get the SQLs from https://github.com/barryvdh/laravel-debugbar.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants