laravel datatable relationships

Edmund Sulzanok picture Edmund Sulzanok · Oct 13, 2015 · Viewed 12.9k times · Source

So in this app Drawing belongsTo Customer. I have datatable

            <table id='drawing-table' class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th>Drawing number</th>
                        <th>Customer</th>
                    </tr>
                </thead>
            </table>

which indicates $darwing->number and $customer->title. To load info I use yajra\Datatables\Datatables;.

Data is loaded with this JS method:

$(function () {
    $('#drawing-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{route('drawings.datatable')}}',
        columns: [
            { data: 'number', name: 'number' },
            { data: 'customer.title', name: 'customer' },
        ]
    });
});

And this Laravel method:

public function datatable()
{
    $drawings = Drawing::select(array('drawings.id','drawings.number'));

    return Datatables::of(Drawing::with('customer')->select('*'))->make(true);
}

QUESTIONS

  1. How do I make datatable search window to work with $customer->title?
  2. How do I display drawing number and customer title as link?

Answer

Edmund Sulzanok picture Edmund Sulzanok · Oct 16, 2015
    public function datatable()
    {

        //reference customer table
        $drawings = DB::table('customers')
            // join it with drawing table
            ->join('drawings', 'drawings.customer_id', '=', 'customers.id')
            //select columns for new virtual table. ID columns must be renamed, because they have the same title
            ->select(['drawings.id AS drawing_id', 'drawings.number', 'customers.title', 'customers.id AS customer_id']);

        // feed new virtual table to datatables and let it preform rest of the query (like, limit, skip, order etc.)
        return Datatables::of($drawings)
            ->editColumn('title', function($drawings) {
                return '<a href="'.route('customers.show', $drawings->customer_id).'">' . $drawings->title . '</a>';
            })  
            ->editColumn('number', function($drawings) {
                return '<a href="'.route('drawings.show', $drawings->drawing_id).'">' . $drawings->number . '</a>';
            })  
            ->make(true);
    }

Spent many hours trying to figure it out, hope it saves someone time. http://datatables.yajrabox.com/fluent/joins