2015-10-12 48 views
1

有3個表,用戶訂單狀態。樞軸表order_status有額外的列:user_idcreated_at(以獲得哪個用戶以及何時設置該狀態)。 訂購模型方法:我如何在數據透視表字段篩選的laravel

// get latest status for order, and tie user (user_id in pivot table)  
public function latestStatus(){ 
     return $this->belongsToMany('Status') 
       ->select(array('*','User.name')) 
       ->orderBy('order_status.created_at','desc') 
       ->join('users','order_status.user_id','=','users.id') 
       ->withTimestamps(); 
       ->limit(1,0); 
     } 

所以,如果我打電話:

$orders = Orders::with('latestStatus')->get(); 

我可以有最新狀態的訂單。沒關係。

我需要有一定的過濾,無論是在訂單屬性,並通過最新的狀態,例如:(表訂單有列位置買家) - 如何把所有的訂單:

order.location_id = in ("ny", "nm") 
order.buyer_id = in ("1", "3") 
order_status.user_id = in ("1", "5") 
order_status.created_at = between (2015-10-04, 2015-10-06) 
order_status.status_id = in ("2", "8", "9") 

呼喚「其中」關於訂單只是解決了定位和買家一部分...

$orders = Orders::whereIn('location_id',["ny", "nm"]) 
     ->whereIn('buyer_id',["1","3"]) 
     ->with('latestStatus') 
     ->get(); 

所以問題是如何在樞軸FIEL過濾ds(查找在特定日期之間創建的具有特定狀態的訂單)?

TNX Ÿ

回答

0

好吧,這裏我是如何做到的:

$orders = Order::with('lateststatus') 
    ->whereHas('lateststatus', function ($q) use ($dateTo, $dateFrom, $statuses) { 
           $q->where('order_status.created_at','>=',$dateFrom); 
           $q->where('order_status.created_at','<',$dateTo); 
           $q->whereIn('order_status.status_id',$statusi); 
          } 
      ); 
$orders = $orders->whereIn('location_id',$locations); } 
$orders = $orders->whereIn('user_id',$users); } 
$orders = $orders->->get(); 

PS:我改變了DB結構,所以我現在要保持user_ID的訂單表。

相關問題