您的声明为您提供您感兴趣的订单集。然后,您可以使用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');
正是我一直在寻找!谢谢! – dulan 2014-11-01 06:23:36