【问题标题】:Laravel 5.4: groupBy on for-loop not working as expectedLaravel 5.4:for 循环上的 groupBy 无法按预期工作
【发布时间】:2018-05-01 10:16:40
【问题描述】:

这是我的控制器首先看到这个控制器很重要

public function index( Request $request ) {
        $dateFrom = $request->get( 'dateFrom' );
        $dateTo   = $request->get( 'dateTo' );
        $status   = $request->get( 'orderState' );

        $orders = ( new OrderList() )
            ->whereHas( 'orderDetail', function ( $query ) {
                $query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
            } )
            ->with( 'deliveryList' )
            ->when( $dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
                $query->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
            } )
            ->when( $status, function ( $query ) use ( $status ) {
                $query->where( 'order_state_id', $status )->get();
            } )->get();

        //Order Status
        $orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();


        return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
    }

这也是OrderListOrderDetail 的模型

class OrderList extends Model {
    protected $fillable = [
        ......
        ......
    ];
    public function orderDetail() {
        return $this->hasMany( OrderDetail::class, 'order_id' );
    }

    public function ....
    ....................
    }
}

class OrderDetail extends Model {
    protected $fillable = [
        ......
        ......
    ];

    public function orderId() {
        return $this->belongsTo( OrderList::class, 'order_id' );
    }

    public function productId() {
        return $this->belongsTo( Product::class, 'product_id' );
    }
}

现在我正在尝试在刀片文件中进行分组

@foreach($orders as $order)
     @foreach($order->orderDetail->groupBy('product_id') as $items)
       <tr>
         <td>{!! $items->sum('quantity') !!}</td>
         <td>{!! $items->first()->product_name !!}</td>
         <td>{!! $items->first()->product_id !!}</td>
       </tr>
     @endforeach
@endforeach

现在这个数组的结果是这样的

-------------------------------------------
product-name   |  quantity  |  product-id | 
-------------------------------------------
Coffey         |     2      |      15     |
Coffey         |     1      |      15     |
Coffey         |     1      |      15     |
tea            |     3      |      22     |
tea            |     2      |      22     |
tea            |     1      |      22     |
-------------------------------------------

我需要它像

-------------------------------------------
product-name   |  quantity  |  product-id | 
-------------------------------------------
Coffey         |     4      |      15     |
tea            |     6      |      22     |
-------------------------------------------

更新

当调试我得到的订单时。

Collection {#708 ▼
  #items: array:14 [▼
    0 => OrderList {#717 ▼
      #fillable: array:4 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [▶]
      #original: array:6 [▶]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: array:5 [▼
        "deliveryList" => null
        "orderedUsers" => User {#756 ▶}
        "orderedStates" => OrderState {#763 ▶}
        "orderDetail" => Collection {#782 ▶}
        "address" => CustomerAddressBook {#791 ▶}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => OrderList {#718 ▶}
    2 => OrderList {#719 ▶}
    3 => OrderList {#720 ▶}
    4 => OrderList {#721 ▶}

如何实现这一点

【问题讨论】:

  • 当你dd($orders);你返回了什么? Illuminate\Support\Collection 还是 Illuminate\Database\Eloquent\Collection?还是OrderList 对象?
  • 据我了解,您质疑它返回 OrderList 对象,每个对象都有自己的 attributesrelations

标签: php laravel for-loop laravel-blade


【解决方案1】:

尝试在您的 orderDetail 关系中添加 groupByselect

$orders = (新订单列表()) ->whereHas('orderDetail', function ($query) { $query->where('supplier_id', Auth::guard('supplier')->user()->id); $query->groupBy('product_id'); $query->select(DB::raw("SUM(quantity) as quantity_total")); })

quantity_total 将持有总量。

希望对您有所帮助。

【讨论】:

  • 不,我不想碰这个查询,因为它正在同一页面上做另一项工作
【解决方案2】:

当您返回 OrderList 而不是 Collection 类型的对象时,您将无法访问 groupBy() 方法。

如果您想将groupBy() 子句应用于基础查询,您可以通过访问查询构建器来实现,如下所示:

$order-&gt;orderDetail()-&gt;groupBy('product_id')

更新

当您有权访问 CollectionEloquentSupport)时,您可以按列表中对象的属性进行分组,如下所示:

$order-&gt;groupBy('product_id');

但是,在您的情况下,我认为您实际上希望按相关对象的属性进行分组。您可以使用. 符号来执行此操作,如下所示:

$order-&gt;groupBy('orderDetail.product_id')

【讨论】:

  • 感谢您为我清除此问题,但我尝试使用此解决方案添加此行,如 @foreach($orders as $order) @foreach($order-&gt;orderDetail()-&gt;groupBy('product_id') as $items)&lt;tr&gt; &lt;td&gt;{!! $items-&gt;sum('quantity') !!}&lt;/td&gt; &lt;td&gt;{!! $items-&gt;first()-&gt;product_name !!}&lt;/td&gt; &lt;td&gt;{!! $items-&gt;first()-&gt;product_id !!}&lt;/td&gt; &lt;/tr&gt; @endforeach @endforeach 但现在它没有显示任何内容!
  • 在使用此$order-&gt;groupBy('orderDetail.product_id')后仍然注意到显示在那里@
猜你喜欢
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2021-04-13
  • 1970-01-01
相关资源
最近更新 更多