本地SQL查询到laravel eloquent查询

时间:2018-04-22 15:42:54

标签: sql laravel join eloquent

我实际上有两个关于此代码的问题。

$cash_advance = DB::select('
        SELECT p1.*, p3.fname, p3.mname, p3.lname 
        FROM cash_advance p1
        INNER JOIN(
            SELECT MAX(created_at) maxdate, customer_id
            FROM cash_advance
            GROUP BY customer_id
        ) p2
        ON p1.customer_id = p2.customer_id
        AND p1.created_at = p2.maxdate
        LEFT JOIN customer as p3 ON p1.customer_id = p3.id
        ORDER BY p1.created_at desc

第一,当使用这种查询而不是标准的雄辩查询时,是否存在任何可能的安全漏洞?

第二是,我怎么能转换这个?这是我一直试图做的示例代码。

$cash_advance = DB::select('p1.*', 'p3.fname', 'p3.mname', 'p3.lname')
        ->from('cash_advance as p1')
        ->join('cash_advance as p2', function($join){
            $join->select(DB::raw('max(created_at) as maxdate'), 'customer_id')
                ->on('p2.customer_id', '=', 'p1.customer_id')
                ->on('p2.maxdate', '=', 'p1.created_at')
                ->groupBy('p2.customer_id');
        })
        ->leftJoin('customer as p3', 'p1.customer_id', '=', 'p3.id')
        ->orderBy('p1.created_at', 'desc');
return \DataTables::of($cash_advance)
    ->addColumn('action', function($cash_advance){
        return '<button class="btn btn-xs btn-info view_cash_advance" id="'.$cash_advance->customer_id.'"><i class="material-icons" style="width: 25px;">visibility</i></button>';//info/visibility
    })
    ->make(true);

但是数据表继续说http://datatables.net/tn/7

ajax代码

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

第一个代码工作,我实际上从stackoverflow中的另一个问题得到了这个想法但是它在本机php而不是larvel上使用,所以我想把它转换为雄辩,以便它更干净和laravel就好。

1 个答案:

答案 0 :(得分:0)

只要您不将任何原始用户输入添加到SQL(不使用绑定),这种查询就不那么安全了。

使用此查询:

$join = DB::table('cash_advance')
    ->select(DB::raw('max(created_at) as maxdate'), 'customer_id')
    ->groupBy('customer_id');
$sql = '(' . $join->toSql() . ') as p2';
$cash_advance = DB::table('cash_advance as p1')
    ->select('p1.*', 'p3.fname', 'p3.mname', 'p3.lname')
    ->join(DB::raw($sql), function($join){
        $join->on('p2.customer_id', '=', 'p1.customer_id')
            ->on('p2.maxdate', '=', 'p1.created_at');
    })
    ->leftJoin('customer as p3', 'p1.customer_id', '=', 'p3.id')
    ->orderBy('p1.created_at', 'desc')
    ->get();