Relationship Error 1 to many in laravel 5.5

1

I am trying to obtain the name of the states of the republic in a one to many relationship:

the model of States the relationship:

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

the model of the employees the relationship:

 public function estados(){
    return $this->belongsTo('App\Models\Estados');
}

I want to get the name of the states and print it in the view, the query is:

$state = DB::table('estados as es')
    ->select(' es.NOMBRE', 'em.Estado_Actual_ID')
    ->join('empleados as em', 'es.id', '=' ,'em.Estado_Actual_ID');

but when I want to print it:

dd($state->NOMBRE);

I get the following error:

Undefined property: Illuminate\Database\Query\Builder::$NOMBRE

what is the problem;

    
asked by Juan Antonio 05.06.2018 в 21:01
source

1 answer

0

We will work the example through the use of eagger loading because when using the Eloquent relationships the problem of N + 1 is generated, therefore to avoid multiple queries and limit it to two we do using the with method that receives as a parameter the name of the method that has some of the Eloquent relationships associated with it

On the Controller EmployeeController (assuming you have it created); create the following method:

public function empleados()
{
   $empleados = Empleado::with('estado')->get();
   return view('vista_name')->with(['empleados' => $empleados]);
}

Inside the previous code you can see that I use eagger loading to do only 2 queries; this you identify with the method with()

Query source: link

Inside the view we can go through the data as follows

@foreach($empleados as $empleado)
    {{ $empleado->nombre }}
    {{ $empleado->estado->nombre }}
@endforeach
  

As you can see in the foreach of the view with the variable   employee accesses the method states that has the logic of belongsTo()   with that you should already be able to access the property name

Observations to your code

  • Within the belongsTo() method the name must be in the singular; that is, state
  • in the method that has hasMany() should be plural employees
  • I armed the answer with what you provide in your question, you just need to adapt to your scenario and try

        
    answered by 13.06.2018 в 02:28