Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
269 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...