Laravel and Datatables as showing an extra field that does not come in the table that I send

0

I would like to know how I can show data from two tables in a single datatable?

In the "user" part, it would be the user's name but it belongs to another table

This is what I have in my controller

namespace App \ Http \ Controllers;

use Illuminate\Http\Request;
use Datatables;
use App\Usuario;
use DB;
use App\Resultado;

class DataTablesController extends Controller
{
    /**
 * Displays datatables front end view
 *
 * @return \Illuminate\View\View
 */
public function datatable()
    {
        return view('usuarios.resultado');
    }

    public function getPosts()
    {
        $model = Usuario::query();
        // return datatables()->eloquent(Usuario::query())->toJson();
        return Datatables::eloquent($model)
        ->addColumn('action', function($user) {
            return '
                    <br><a href="' . route('VerResultado', $user->id_usu) . '" class="btn btn-xs btn-success" title="Detalles">Ver Detalles</a>
                ';
        })
        ->toJson();

    }

    public function getRes()
    {
        $resultado = Resultado::query();

        return Datatables::eloquent($resultado)
        ->toJson();
    }
}

And this is basically the ajax function.

  $('#resultado').DataTable({
      dom: 'Bfrtip',
      "procesing": true,
      "serverside": true,
       responsive: true,
       buttons: [
      'copy', 'csv', 'excel', 'pdf', 'print' 
      ],
      "ajax": '{{ route('datatable/getres') }}',
      "columns":[ 
        {data: 'id', name: 'id'}, 
        {data: 'sintetico', name: 'sintetico'},
        {data: 'idealista', name: 'idealista'},
        {data: 'pragmatico', name: 'pragmatico'},
        {data: 'analitico', name: 'analitico'},
        {data: 'realista', name: 'realista'},
        {data: 'total', name: 'total'},
        {data: 'id_usu', name: 'id_usu'},
      ],
      order: [[0, 'asc']]
    });
});
    
asked by Dohko19 22.10.2018 в 23:54
source

1 answer

0

what you have to do is use the function belongsto in laravel, in the query you should add the following line

Resultado::with('usuario_pk')->get();

in the Result model you must define a function called user_pk, and where App \ users corresponds to the table of foreign data
and the hasMany function allows me to bring 1 to many data

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Resultado extends Model {

    protected $table    = 'resultado';
    protected $fillable = [];

    public function usuario_pk() {
        return $this->belongsTo('App\users', 'id_usu');
    }
    public function especie_id_all() {
        return $this->hasMany('App\ArbolesModel', 'barrio_id');
    } 
}

and in the view bring the data user_pk- > name

 {data: 'usuario_pk->name', name: 'usuario_pk->name'},
    
answered by 23.10.2018 в 04:12