Laravel groupby周Eloquent查询

时间:2014-10-29 13:00:23

标签: php sql laravel laravel-4 eloquent

作为Laravel的新手,我对日期格式化程序和刀片模板有些疑虑。

我写了一个以正确方式执行的查询, 以下是我的Eloquent SQL查询。

public function orderbyweek()
    {

        $orderbyweek = DB::table('sales_flat_order_items as s')
                ->leftJoin('sales_flat_orders as w', 'w.entity_id','=','s.order_id')
                ->select(array(DB::Raw('sum(s.amount_refunded) as amount_refunded'),
                    DB::Raw('sum(s.row_total) as row_total'),
                    DB::Raw('sum(s.discount_amount) as discount_amount'),
                    DB::Raw('sum(s.tax_amount) as tax_amount'), 
                    DB::Raw('sum(s.qty_ordered) as qty_ordered'),
                    DB::Raw('sum(w.subtotal) as subtotal'),
                    DB::Raw('WEEK(w.created_at) week'), 
                    DB::Raw('sum(w.total_invoiced) as total_invoiced'),
                    DB::Raw('sum(w.shipping_amount) as shipping_amount')
                    ))
                ->where('qty_canceled','=','0')
                ->where('status','!=','canceled')
                ->groupBy('week')
                ->orderBy('w.created_at')
                ->get();

            return View::make('sales_flat_orders.orderbyweek', compact('orderbyweek'));


    }

这向我展示了我希望这个星期在7天的间隔中的表格。 所以在我的模板中我需要做什么?如何为此添加日期格式化程序?我在这里做了一些事情:

<table width="100%">
    <thead>

        <th>DATE</th>
        </thead>

  @foreach($orderbyweek as $s)

  <tr>
     <td>{{date("d F, Y",strtotime($s->week))}}</td>

  </tr>

 @endforeach
</table>

我执行了以下的SQL查询:

select sum(s.amount_refunded) as amount_refunded, sum(s.row_total) as row_total, sum(s.discount_amount) as discount_amount, sum(s.tax_amount) as tax_amount, sum(s.qty_ordered) as qty_ordered, sum(w.subtotal) as subtotal, WEEK(w.created_at) week, sum(w.total_invoiced) as total_invoiced, sum(w.shipping_amount) as shipping_amount from `sales_flat_order_items` as `s` left join `sales_flat_orders` as `w` on `w`.`entity_id` = `s`.`order_id` where `qty_canceled` = '0' and `status` != 'canceled' group by `week` order by `s`.`created_at` asc

我哪里错了?

我正在获得ordebydate,也是顺序。但不按周排序

U can see the image of the table, Here see the week, Its not the porper one

请帮帮我。

1 个答案:

答案 0 :(得分:1)

我用这个月分组,我想这也适用于一周。

    $data = \Invoice::select(   
                        DB::raw("MONTHNAME(STR_TO_DATE(MONTH(date), '%m')) as month"),
                        DB::raw('SUM(g_total) as total_invoice_amnt'),
                        DB::raw('MONTH(date) as no_mnth')
                    );
                    foreach ($filters as $filter) {
                        if ($filter[2] != '') {
                            $data->where($filter[0], $filter[1], $filter[2]);
                        }
                    }
    $data = $data->groupBy("month")
                 ->OrderBy('no_mnth','ASC')
                 ->get()
                 ->toArray();

    return $data;