Consult twice the same table

4

I have the holiday table which has two fields, one that is authorize_id and request_id, makes references to the same employee table, I can already show the name of the one who authorizes by means of the id, but I do not know how to show the name of the one who requests.  here my code:

 protected $rules = array(
    'nombre' => 'required|max:50'
);

public function index()
{
    $grupos = DB::table('vacaciones')
    ->LeftJoin('empleados', 'empleados.id','=', 'vacaciones.autoriza_id')
    ->select('vacaciones.*', 'empleados.nombre')
    ->get();

return response()->json(
    $grupos->toArray()
); 
    
asked by SoyKrut 28.08.2018 в 19:45
source

1 answer

1

For what you want to do, my solution would be for you to have your models well created using the php artisan make:model NombreModelo command, once created as shown below:

Model Vacaciones :

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Vacaciones extends Model
{
   //Atributos



  //Relaciones
  public function solicitante(){
     return $this->belongsTo('App\Models\Empleado', 'solicita_id');
  }

  public function autoriza(){
     return $this->belongsTo('App\Models\Empleado', 'autoriza_id');
  }

}

Employed Model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Empleado extends Model
{
   //Atributos



  //Relaciones
  public function vacacionesSolicitante(){
     return $this->hasMany('App\Models\Empleado', 'solicita_id');
  }

  public function vacacionesAutoriza(){
     return $this->hasMany('App\Models\Empleado', 'autoriza_id');
  }

}

If your driver wants to obtain who authorizes and who requests vacations from a record of the vacation table, it would be enough:

//Importar Modelo hasta arriba
use App\Models\Vacaciones;

//Método dentro de tu controlador

public function obtenerDatos(){
   $id = 1;
   $vacaciones = Vacaciones::where('id', $id)->with('solicitante', 'autoriza')->first();

   //Aquí ya tienes los datos que necesitas

   $nombre_solicitante = $vacaciones->solicitante->nombre;
   $nombre_autoriza = $vacaciones->autoriza->nombre;
}

And now, there you have your data, do not try to avoid using Laravel's Eloquent ORM, it really helps you too, you should only use "raw" expressions when it is really necessary and there is no other. / p>     

answered by 28.08.2018 в 23:47