laravel datatable

使用yajra/laravel-datatables

默认的方式都是使用eloquent 但是对于复杂数据的查询会有问题 使用DB::select可以直接查询sql

Route:

Route::get('datatables/datatable','DatatablesController@getIndex');
Route::get('datatables/anyData','DatatablesController@anyData')->name('datatables.data');

Controller:

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\User;
use Yajra\Datatables\Datatables;
use DB;

class DatatablesController extends Controller
{
    /**
     * Displays datatables front end view
     *
     * @return \Illuminate\View\View
     */
    public function getIndex()
    {
        return view('datatables.index');
    }

    /**
     * Process datatables ajax request.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function anyData()
    {
//        $users = User::select(['id', 'name', 'email', 'password', 'created_at', 'updated_at']);

        $sql = "select id, name, email, created_at, updated_at,id from users";
        $users = DB::select($sql);

        return Datatables::of($users)
        ->addColumn('action', function ($user) {
            return '<a href="#edit-' . $user->id . '" class="btn btn-xs btn-primary"><i class="glyphicon glyphicon-edit"></i> Edit</a>';
        })
        ->make(true);
    }
}

View:

@extends('layouts.master')

@section('content')
    {{ Breadcrumbs::render('home') }}
    <table class="table table-bordered" id="users-table">
        <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Created At</th>
            <th>Updated At</th>
            <th>Action</th>
        </tr>
        </thead>
    </table>
@stop

@push('scripts')
    <script>
        $(function() {
            $('#users-table').DataTable({
                processing: true,
                serverSide: true,
                ajax: '{!! route('datatables.data') !!}',
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'name', name: 'name' },
                    { data: 'email', name: 'email' },
                    { data: 'created_at', name: 'created_at' },
                    { data: 'updated_at', name: 'updated_at' },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ]
            });
        });
    </script>
@endpush

image.png