Laravel 数据库 聚合+Join 查找语句。

it2026-02-23  9

聚合#

查询构造器也提供各式各样的聚合方法,如 count, max, min, avg 及 sum。

使用聚合方法#

$users = DB::table('users')->count(); $price = DB::table('orders')->max('price'); $price = DB::table('orders')->min('price'); $price = DB::table('orders')->avg('price'); $total = DB::table('users')->sum('votes');

但是对于复杂的情况(比如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 /** * sales deb export. * @param * @return .csv */  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);        } 

转载于:https://www.cnblogs.com/Uncle-liu/p/7401641.html

最新回复(0)