Php 可以在Laravel中执行orderBy()或orderBy()吗?

Php 可以在Laravel中执行orderBy()或orderBy()吗?,php,laravel,laravel-query-builder,Php,Laravel,Laravel Query Builder,是否可以在Laravel Eloquent中执行orderBy()或orderBy()?我当前的查询仅在用户单击前端上的排序时对item.ItemID进行排序,但在用户单击前端上的排序时,它不会对item.Desc进行排序 我曾尝试使用闭包将这些orderBy()s放入where()子句中,但也没有成功。有人知道我能纠正这个问题的好方法吗 $this->model ->加入('awards'、'item.ItemID'、'='、'awards.LinkID') ->加入('opportuniti

是否可以在Laravel Eloquent中执行
orderBy()
orderBy()
?我当前的查询仅在用户单击前端上的排序时对
item.ItemID
进行排序,但在用户单击前端上的排序时,它不会对
item.Desc
进行排序

我曾尝试使用闭包将这些
orderBy()
s放入
where()
子句中,但也没有成功。有人知道我能纠正这个问题的好方法吗

$this->model
->加入('awards'、'item.ItemID'、'='、'awards.LinkID')
->加入('opportunities'、'awards.AwardID'、'='、'branch.AwardID')
->groupBy('item.ItemID'、'item.Desc')
->orderBy('item.ItemID',$ClickedInventoryItemIDFlag?'DESC':'ASC')
->orderBy('item.Desc',$clickedDescriptionColumnFlag?'Desc':'ASC')
->选择(“item.ItemID”、“item.Desc”、“branch.OppID”)
->get();

SQL中的排序是累积的,因此您总是按第一项排序,然后按第二项排序。相反,您可以:

$this->model
->加入('awards'、'item.ItemID'、'='、'awards.LinkID')
->加入('opportunities'、'awards.AwardID'、'='、'branch.AwardID')
->groupBy('item.ItemID'、'item.Desc')
->什么时候(
$clickedDescriptionColumnFlag,//条件
fn($q)=>$q->orderBy('item.Desc')//true
fn($q)=>$q->orderBy('item.ItemID')//false
)
->选择(“item.ItemID”、“item.Desc”、“branch.OppID”)
->get();
但我必须说,每当我看到查询生成器连接像这样发生时,都会有一面大旗告诉我您可能不理解。(事实上,你在标题中使用了“雄辩的”,尽管问题中没有这样的代码!)我强烈建议研究如何工作;对于除最重负载外的所有负载,编码效率的提高远远超过数据库查询效率的略微降低。

直到调用
get()
方法,它都是查询生成器,因为所有链接方法都返回
self
实例。因此,您可以在需要时分离链并使用if block:

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

我不明白你所说的“orderBy()”或“orderBy()”
,是什么在解决这个“或”?@lagbox我的意思是-是否可以将排序分开,以便用户在单击时可以选择一次排序一个?是否需要一个条件来决定使用哪个orderBy?@lagbox是的,这就是我的意思,对此很抱歉。您可以使用
if
语句或使用生成器的
when
方法检查值并相应地执行操作