我正在尝试过滤来自数据库的数据。
以下是完整查询
public function index(Request $request)
{
$dateFrom = $request->get('dateFrom', Carbon::now()->subYears(10)->toDateTimeString());
$dateTo = $request->get('dateTo', Carbon::today());
$status = $request->get('orderState');
$orders = (new OrderDetail())
->where('supplier_id', Auth::guard('supplier')->user()->id)
->whereBetween('created_at', [$dateFrom, $dateTo])
->whereHas('orderId', function ($query) use ($status) {
$query->where('order_state_id', $status);
})
->groupBy('order_id')
->get();
//Order Status
$orderStates = OrderState::listsTranslations('states')->pluck('states', 'id')->toArray();
return view('supplierComponents.order_list', compact('orders', 'orderStates'));
}
现在,如果客户端未选择$status
,则结果为空。
如何将默认$status
设置为全部,或者只是在查询中忽略它而不必再进行其他查询?
答案 0 :(得分:2)
你需要这样的东西:
$orders = ( new OrderDetail() )
->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )
->whereBetween( 'created_at', [ $dateFrom, $dateTo ] );
if($status){
$orders = $orders->whereHas( 'orderId', function ( $query ) use ( $status ) {
$query->where( 'order_state_id', $status );
});
}
$orders = $orders->groupBy( 'order_id' )
->get();
答案 1 :(得分:1)
$orders = ( new OrderDetail() )
->where( 'supplier_id', Auth::guard( 'supplier' )->user()->id )
->whereBetween( 'created_at', [ $dateFrom, $dateTo ] )
->whereHas( 'orderId', function ( $query ) use ( $status ) {
if(isset($status)) $query->where( 'order_state_id', $status );
} )`enter code here`
->groupBy( 'order_id' )
->get();
答案 2 :(得分:1)
作为@ fico7489答案的替代方案,您还可以使用when()
方法:
$orders = (new OrderDetail())
->where('supplier_id', Auth::guard('supplier')->user()->id)
->whereBetween('created_at', [$dateFrom, $dateTo])
->when($status, function ($query) use ($status) {
$query->whereHas('orderId', function ($query) use ($status) {
$query->where('order_state_id', $status);
});
})
->groupBy('order_id')
->get();