繁体   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