【问题标题】:Laravel 5.8 How to order by sum of pivot table value in foreach?Laravel 5.8 如何在 foreach 中按数据透视表值的总和排序?
【发布时间】:2019-03-04 20:46:53
【问题描述】:

我有以下表格:

零件:

id | name
1  | Lock
2  | Light

货架:

id | name
1  | 1A
2  | 1B

part_shelf

id | part_id | shelf_id | stock
1  | 1       | 1        | 5
2  | 1       | 2        | 10
3  | 2       | 1        | 4

关系:

在零件模型中:

public function shelves()
{
    return $this->belongsToMany( Shelf::class )->withPivot( 'stock' );
}

在货架模型中:

public function parts()
{
    return $this->belongsToMany(Part::class)->withPivot('stock');
}

我想做的是根据数据透视表的总库存订购所有零件。

我尝试过的如下:

$parts = Part::all(); // This is inside controller

@foreach($parts->shelves()->orderBy('pivot_stock', 'desc') as $part)
@foreach($parts->shelves()->orderBy('part_shelf.stock', 'desc') as $part)

我知道我可以通过以下方式获得单个零件的总库存:

$part->shelves()->sum('stock')

我只是不知道如何处理 foreach 循环中的所有部分。

还查看了其他问题,但这并没有真正帮助:

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我有类似的问题。我有三张桌子。玩家(在我的代码“Igrac”中)、锦标赛(在我的代码“Turnir_Piramida”中)和 player_tournaments 数据透视表(在我的代码“Nastup_piramida”中)。在数据透视表中,每场比赛中每个球员的得分也是列点。我需要总结每个玩家的分数,然后按分数总和对表格进行排序。

    我设法通过您发布的第三个链接来做到这一点。你可以在这个link看到我的解决方案

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2020-03-27
      • 2012-09-24
      • 2020-06-16
      • 1970-01-01
      • 2017-09-18
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多