如何在Eloquent
中的groupBy
中使用whereHas
这是我的查询
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 );
} )
->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();
//dd( $orders );
//Order Status
$orderStates = OrderState::listsTranslations( 'states' )->pluck( 'states', 'id' )->toArray();
return view( 'supplierComponents.order_list', compact( 'orders', 'orderStates' ) );
}
我需要按order_id
orderDetail
中存在的->whereHas( 'orderDetail', function ( $query ) {
$query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )->groupBy('order_id');
} )
对订单列表进行分组
我试着这样做
order_id
更新
订单列表详情已groupBy
我需要order_list为dd($orders) results
11 => OrderList {#723 ▼
#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:1 [▼
"orderDetail" => Collection {#741 ▼
#items: array:1 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#relations: array:1 [▼
"orderDetail" => Collection {#741 ▼
#items: array:1 [▶]
}
看到这个
<!-- ko foreach: AllPens -->
<label>
<input type="checkbox" data-bind="checked: IsChecked" />
<span data-bind="text: name"></span>
</label>
<!-- /ko -->
如果它被分组,它应该将相关项目分组到这里,但它会以这种方式发生
但这不起作用,应该采取什么样的正确方法呢?
答案 0 :(得分:0)
$orders = ( new OrderList() )
->whereHas( 'orderDetail', function ( $query ) {
$query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id );
} )
->with(['orderDetail' => function ($query) {
$query->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )->groupBy('order_id');
}])
->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();
不会给你小组,你必须再次得到关系数据。使用以下内容:
{{1}}
答案 1 :(得分:0)
$orders = Order::join('orderDetail',function($q){
$q->on('orderDetail.your_id','orders.id');
$q->where('supplier_id', Auth::guard('supplier')->user()->id);
})
->select(['orders.user_id','orderDetail.order_id'])
->when($dateFrom, function ( $query ) use ( $dateFrom, $dateTo ) {
$query->whereBetween('orders.created_at', [ $dateFrom, $dateTo ] );
})
->when($status, function ( $query ) use ( $status ) {
$query->where( 'orders.order_state_id', $status );
})
->groupBy('orderDetail.order_id')
->get();