orderBy不在laravel + datatable中工作

时间:2018-04-15 16:52:56

标签: laravel datatable controller sql-order-by

我只想获得每个客户ID的最新日期/时间,但orderBy代码似乎无法正常工作。我已经尝试过使用,但我一直在获取数据表错误7。

控制器

while ($row = $this->statement->fetch(PDO::FETCH_ASSOC))

数据表

public function refresh(){
    $cash_advance = DB::table('cash_advance')
        ->join('customer', 'customer.id', '=', 'cash_advance.customer_id')
        ->select('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.created_at', 'cash_advance.balance')
        ->groupBy('cash_advance.customer_id')
        ->orderBy('cash_advance.created_at', 'desc')
        ->get();
    return \DataTables::of($cash_advance)
    ->addColumn('action', function($cash_advance){
        return '<button class="btn btn-xs btn-info" id="'.$cash_advance->customer_id.'"><i class="material-icons" style="width: 25px;">visibility</i></button>';//info/visibility
    })
    ->make(true);
}

output database

1 个答案:

答案 0 :(得分:0)

获取最新日期只需使用max aggregatormax('cash_advance.created_at')

但无论如何在上面的groupBy语句中,你应该选择所有与客户相关的功能 像这样:

    DB::table('cash_advance')
    ->join('customer', 'customer.id', '=', 'cash_advance.customer_id')
    ->select('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance', DB::raw('MAX( cash_advance.created_at)'))
    ->groupBy('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance',)
    ->orderBy('cash_advance.customer_id', 'customer.fname', 'customer.mname', 'customer.lname', 'cash_advance.amount', 'cash_advance.balance', 'desc')
    ->get();