Reputation: 83
Is it possible to do orderBy()
or
orderBy()
in Laravel Eloquent? My current query only sorts the item.ItemID
upon user clicking sort on the frontend but it won't sort item.Desc
when the user clicks sort on the frontend.
I've tried putting these orderBy()
s inside of a where()
clause using a closure but that didn't work either. Does anyone know of a good way I could rectify this?
$this->model
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc')
->orderBy('item.ItemID', $clickedDInventoryItemIdFlag ? 'DESC' : 'ASC')
->orderBy('item.Desc', $clickedDescriptionColumnFlag ? 'DESC' : 'ASC')
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();
Upvotes: 0
Views: 3596
Reputation: 7111
Until you call get()
method it is all query builder since all chaining methods return self
instance. So you can separate chain and use if block when needed:
$someModels = $this->SomeModel
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc');
if ($condition) {
$someModels->orderBy('item.ItemID', $clickedDInventoryItemIdFlag ? 'DESC' : 'ASC')
} else {
$someModels->orderBy('item.Desc', $clickedDescriptionColumnFlag ? 'DESC' : 'ASC');
}
$someModels
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();
Upvotes: 0
Reputation: 42697
Ordering in SQL is cumulative, so you'll always be ordering by the first item, then the second. Instead you can manipulate the query based on a condition:
$this->model
->join('awards', 'item.ItemID', '=', 'awards.LinkID')
->join('opportunities', 'awards.AwardID', '=', 'branch.AwardID')
->groupBy('item.ItemID', 'item.Desc')
->when(
$clickedDescriptionColumnFlag, // condition
fn ($q) => $q->orderBy('item.Desc') // true
fn ($q) => $q->orderBy('item.ItemID') // false
)
->select("item.ItemID", "item.Desc", "branch.OppID")
->get();
I have to say though, whenever I see query builder joins happening like this, it's a big flag telling me that you likely don't understand model relationships. (And the fact that you used "Eloquent" in your title, despite there being no such code in the question!) I would strongly suggest looking into how Eloquent works; for all but the heaviest loads the increase in coding efficiency far outweighs the slight decrease in database query efficiency.
Upvotes: 1