Make a correct query of two tables

0

I'm having a problem with a query in Laravel where two tables are related: Empleados and Emergencias in a 1: N relationship. According to me, I have good relationships in my models that are the following.

Employee

    class Empleado extends Model
    {
       use SoftDeletes; 

       protected $table    = 'empleados';
       protected $fillable = ['id', 'nombre', 'apellido', 'fechaNac', 'telefono', 'celular', 
                               'celularEmp', 'email', 'emailEmp','color', 'departamento',
                               'puesto', 'sueldo];
       protected $dates    = ['deleted_at'];
       public $timestamps  = true;

       public function emergencias()
       {
          return $this->hasMany('Valach\Emergencia', 'empleado_id', 'id');
       }

       public static function getEmpleados()
       {
          return DB::table('empleados')
                   ->leftJoin('emergencias', 'empleados.id', '=', 'emergencias.empleado_id')
                   ->get();
       }
    }

Emergency

    class Emergencia extends Model
    {
       protected $table      = 'emergencias';
       protected $primaryKey = 'empleado_id';
       protected $fillable   = ['empleado_id', 'tel', 'cel', 'contacto'];
       public $timestamps    = false;

       public function empleado()
       {
          return $this->belongsTo('Valach\Empleado');
       } 
    }

What I want to do is print the data of all employees along with all the emergency numbers that correspond to that employee . As seen in the employee model, I have a method with which I do the query and when printing with dd($empleado) it brings me the following:

  • If I have the employee id = 1 and it has two emergency records, it prints me two fixes, each one with the employee id but equal each one with a different register of emegercia.

What I'm looking for is to print a single arrangement with the id = 1 and within it, an arrangement with all the emergency records that are available.

Here are some screenshots of how I'm getting the fix, I was not allowed to put the whole image so I just put where the emergency data is printed.

I would greatly appreciate your help.

    
asked by Jorge Fernandez 10.03.2017 в 16:26
source

2 answers

1

Eloquent does that for you. if you want all the employees with their emergencies you just have to write:

$empleados= Valach\Empleado::with('emergencias')->get();

a single serious employee:

$empleado= Valach\Empleado::findOrFail(1);
$empleado = $empleado->load('emergencias');
    
answered by 10.03.2017 / 17:20
source
0

Use "with" or "load".

$Empleados = Valach\Empleado::with('emergencias');

or you can use:

$Empleados = Valach\Empleado::all();
$Empleados = $Empleados->load('emergencias');
    
answered by 10.03.2017 в 17:15