Combining relationship sorting and filtering

- 1 answer

Ad

I have two models: Item and Category. The Item model has a category_id field which is a foreign key of the category.

On the search page I am currently performing filtering. This is done via a series of where() clauses, for example

if($request->input('location_id', "") != "") {
    $query->where('location_id', '=', $request->input('location_id'));
}

These are contained within the scope search(), so they are called like this:

$results = Item::search($request)->get();

I now want to apply sorting to the results, firstly by the name column of the category, then by the product_number column on the items table.

How would I go about doing this without interfering with the filtering in the search scope?

Ad

Answer

Ad

Just add multiple calls to orderBy():

$results = Item::search($request)
  ->join('categories', 'category_id', '=', 'categories.id')
  ->select('items.*')
  ->orderBy('categories.name')
  ->orderBy('product_number')
  ->get();
Ad
source: stackoverflow.com
Ad