簡體   English   中英

如何根據具有一對多關系的列進行排序

[英]How to sort based on a column with a one to many relationship

我想做的是:

我有兩個具有一對多關系的表

部門

id
name
position
set_plan_id

座位計划

id
name
order

我想根據seat_plans中存在的順序字段對所有扇區進行排序(它是數字類型,因此按升序排序)。

我試過這段代碼,但我得到了未分類的扇區。

$sectors= Sector::whereHas('seat_plan', function ($query) {                                         
            $query->orderBy('order'); 
        })->get();

任何人都可以幫助我嗎? 謝謝你們

您可以選擇像這樣與表進行連接:

$sectors = Sector::join('seat_plans', 'seat_plans.id', '=', 'sectors.seat_plan_id')
    ->orderBy('seat_plans.order')
    ->select('sectors.*')
    ->get();

或者使用如下所示的聚合方法:

$sectors = Sector::withAggregate('seat_plan', 'order')
   ->orderBy('seat_plan_order')
   ->get();

參考: https://laravel.com/api/9.x/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.html#method_withAggregate

嘗試這個:

Sector::select('sectors.*')
    ->join('seat_plans', 'seat_plans.id', 'sectors.seat_plans_id')
    ->orderBy('seat_plans.order')
    ->get();

有關更多方法,請查看此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM