【问题标题】:orderBy not working in laravel + datatableorderBy 不能在 laravel + 数据表中工作
【发布时间】:2018-09-25 10:26:45
【问题描述】:

我只想获取每个客户 ID 的最新日期/时间,但 orderBy 代码似乎不起作用。我已经尝试过使用,但我不断收到数据表错误 7。

控制器

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);
}

数据表

var cash_advancetable = $('#cash_advancetable').DataTable({
            dom: 'Bfrtip',
            buttons: [
            ],
            processing: true,
            serverSide: true,
            ajax: "{{ route('refresh_cashadvance') }}",
            columns: [
                {render: function(data, type, full, meta){
                    return full.fname +" "+full.mname+" "+full.lname;
                }},
                {data: 'amount', name: 'amount'},
                {data: 'created_at', name: 'created_at'},
                {data: 'balance', name: 'balance'},
                {data: "action", orderable:false,searchable:false}
            ]
        });

output database

【问题讨论】:

  • 错误是什么?
  • 没有错误,只是当我使用 group by 时,它需要插入最早的数据而不是最新的数据,降序的顺序不像我想象的那样工作。
  • orderBy()之后尝试使用groupBy()
  • 我也试过了,但是没用。
  • 如果我知道 mysql 抛出什么错误信息(7 除外),我可以提供帮助

标签: laravel datatable controller sql-order-by


【解决方案1】:

要获取最新日期,只需使用 max aggregator: max('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();

【讨论】:

  • 我仍然得到相同的结果。
  • 为什么你不使用 max laravel 聚合器? laravel.com/docs/5.5/queries#Aggregates
  • 如何使用它?因为我之前试过了,没用
  • 尝试更新代码后出现此错误。 DataTables 警告:table id=cash_advancetable - 为第 0 行第 2 列请求未知参数“created_at”。有关此错误的更多信息,请参阅datatables.net/tn/4
  • 我尝试使用 latest(),它在我的系统的一部分中工作,但在这一部分中不起作用。
猜你喜欢
  • 2016-02-23
  • 2022-11-02
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
相关资源
最近更新 更多