2014-10-30 50 views
0

我有3个表,产品订单order_product,第三一个是包含一个名为product_quantity字段记录产品质量的有关顺序的旋转表到相应的产品。现在,我要计算在一定时期内销售的产品总,我拿来的订单,像这样:Laravel总结领域旋转表

Order::whereBetween('created_at', array($start_date, $end_date))->where('status', $order_status_completed)->get() 

而接下来卡住了,我当然不希望遍历每个牵强为了总结product_quantity起来,因为就我所知,这只是一种杀死性能的方法,只要使用 - > sum('product_quantity'),我就可以做到这一点?

回答

1

您的声明为您提供您感兴趣的订单集。然后,您可以使用ID列表来查询order_product表。喜欢的东西:

// get the orders 
$orders = Order::whereBetween('created_at', array($start_date, $end_date))->where('status', $order_status_completed)->get(); 

// get an array of the ids 
$orderIds = $orders->lists('id'); 

// sum the order_product.product_quantity for the related orders 
$total = DB::table('order_product')->whereIn('order_id', $orderIds)->sum('product_quantity'); 

如果你不关心顺序对象本身,你可以直接将IDS:

// get the order ids 
$orderIds = Order::whereBetween('created_at', array($start_date, $end_date))->where('status', $order_status_completed)->lists('id'); 

// sum the order_product.product_quantity for the related orders 
$total = DB::table('order_product')->whereIn('order_id', $orderIds)->sum('product_quantity'); 

如果你想使用子查询,而不是两个单独的查询,你可以这样做:

$total = DB::table('order_product') 
    ->whereIn('order_id', function($q) use ($start_date, $end_date, $order_status_completed) { 
     $q->select('id') 
      ->from((new Order())->getTable()) 
      ->whereBetween('created_at', array($start_date, $end_date)) 
      ->where('status', $order_status_completed); 
    }) 
    ->sum('product_quantity'); 
+0

正是我一直在寻找!谢谢! – dulan 2014-11-01 06:23:36