Laravel中eager loading预加载关联表时orderBy排序失效问题求助
问题原因
你当前写法中with闭包内的orderBy仅会对预加载的inventoryPrice关联数据本身做排序,不会作用于主表Inventory的结果排序,这是Laravel Eager Loading的固有机制:预加载的查询约束仅作用于关联表的查询,不会影响主表的查询逻辑。
实现方案
因为是一对一关联,可通过以下两种常用方式实现主表按关联字段排序:
方案1:使用join关联查询(兼容性最高)
适合所有Laravel版本,可灵活处理关联条件:
// 如需保留无对应关联记录的Inventory数据,可将join改为leftJoin $inventoryFilterQuery = Inventory::select('inventories.*') ->join('inventory_prices', 'inventories.id', '=', 'inventory_prices.inventory_id') ->orderBy('inventory_prices.inventory_price', 'desc') ->with('inventoryPrice') ->get();
方案2:使用withAggregate(Laravel 6+ 支持,写法更简洁)
无需手动编写关联逻辑,框架自动生成聚合字段:
// withAggregate第二个参数为关联表要取值的字段,自动生成别名为`{关联名}_{字段名}` $inventoryFilterQuery = Inventory::withAggregate('inventoryPrice', 'inventory_price') ->orderBy('inventory_price_inventory_price', 'desc') ->with('inventoryPrice') ->get();
也可以自定义别名简化排序字段:
$inventoryFilterQuery = Inventory::withAggregate('inventoryPrice as price', 'inventory_price') ->orderBy('price', 'desc') ->with('inventoryPrice') ->get();
内容的提问来源于stack exchange,提问作者Mubashir Khan
相关产品推荐
相关产品推荐

