Laravel Relationship in Datatable server side

0

Would there be any way to pass the model relationship to the columns of the Datatable server side?

For example in the Datatable script:

columns: [
    { data: 'marca_id', name: 'marca_id' },
    { data: 'automovel_modelo', name: 'automovel_modelo' },
    { data: 'action', name: 'action', orderable: false, searchable: false}
],

Where tag_id would have to receive the relationship value to display the tag name according to ID.

Function in model with relationship:

public function marca(){
    return $this->belongsTo('App\Models\Config\Transito\AutomovelMarca');
}

Controller that displays data:

public function getData ()
{
    $automovel_modelo = AutomovelModelo::all();

    return Datatables::of($automovel_modelo)
    ->addColumn('action', function($automovel_modelo){
        return 
            '<a href="automoveis_modelos/'. $automovel_modelo->id .'/edit" class="btn btn-xs btn-warning" title="Editar">
               <i class="fa fa-pencil"></i>
            </a>' .
            '<a onclick="deleteData('. $automovel_modelo->id .')" class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
    })
    ->make(true);


    return datatables(AutomovelModelo::query())->toJson();

}

But I did not figure out how to move the relationship to json.

    
asked by anonymous 19.09.2018 / 13:36

1 answer

1

So I understand, you want to pass the values of marca of each AutomovelModelo to Datatable , except that you are not loading this information. To do this, use the with function to load the relationship with marca , like this:

$automovel_modelo = AutomovelModelo::with('marca')->get();

In this way, you will load all information from marca to each AutomovelModelo .

As for displaying on your Datatable , I would not know how to do it, but I think if this { data: 'automovel_modelo', name: 'automovel_modelo' }, line displays information for each column of AutomovelModelo , you would have to replace marca_id with only marca in the columns of your script of Datatable .

References:

20.09.2018 / 17:18