Laravel 数据库 聚合+Join 查找语句。
时间:2021-07-01 10:21:17
帮助过:13人阅读
但是对于复杂的情况(比如join 后的结果,其结果并不是个objet)。就不能直接使用上述的方法
解决方法:
db::raw(‘‘)
Raw Expressions#
有些时候您需要使用 raw expression 在查询语句里,这样的表达式会成为字串插入至查询中,因此要小心勿建立任何 SQL 注入的攻击点。要建立 raw expression,您可以使用 DB::raw
方法:
使用 Raw Expression#
$users = DB::table(‘users‘)
->select(DB::raw(‘count(*) as user_count, status‘))
->where(‘status‘, ‘<>‘, 1)
->groupBy(‘status‘)
->get();
实际代码:
[php] view plain
copy
- private function _salesDEBExport()
- {
- $objects = DB::table(‘orders‘)
- ->join(‘order_products‘,‘orders.id‘,‘=‘,‘order_products.order_id‘)
- ->join(‘products‘,‘order_products.product_id‘,‘=‘,‘products.id‘)
- ->leftJoin(‘categories‘,‘products.category_id‘,‘=‘,‘categories.id‘)
-
- ->select(
- ‘orders.external_id‘,
- ‘orders.address_billing_name‘,
- ‘categories.customs_code‘,
- ‘orders.external_sale_date‘,
- ‘orders.invoice_external_id‘,
- ‘orders.payment_method‘,
- ‘orders.address_shipping_country‘,
- DB::raw(‘
- SUM(order_products.amount_base) AS amount_base,
- SUM(order_products.amount_tax) AS amount_tax,
- SUM(order_products.amount_total) AS amount_total
- ‘)
- )
- ->groupBy(‘orders.external_id‘,‘categories.customs_code‘)
- ->whereIn(‘orders.object_state_id‘, array(2,3))
- ->where(‘orders.created_at‘, ‘like‘, Input::get(‘year‘) . ‘-‘ . Input::get(‘month‘) . ‘-%‘)
- ->get();
-
- if (empty($objects))
- {
- Notification::error("Aucune donnée disponible.");
- return Redirect::to(URL::previous());
- }else{
- $headers = array(
- ‘Content-Type‘ => ‘text/csv‘,
- ‘Content-Disposition‘ => ‘attachment; filename="sales_deb_export_‘.Input::get(‘month‘).‘_‘.Input::get(‘year‘).‘.csv"‘,
- );
-
- $output = rtrim(implode(‘,‘, array_keys((array) $objects[0]))) . "\n";
- foreach($objects as $object)
- {
- $output .= rtrim(implode(‘,‘, (array) $object)) . "\n";
- }
- return Response::make($output, 200, $headers);
-
- }
Laravel 数据库 聚合+Join 查找语句。
标签:mount ons function pre view div highlight country previous