How to consult records between two related tables in laravel

1

I want to make the query of a section table and of it to show the data of another table that is related, called semesters. I need help on how to consult it in the controller and how to display the data in the view

My controller

public function registros()
    {
         $seccion=Seccion::paginate (5);
return view ('/registros-secciones',compact('seccion') );


    }

in my view

{{$ section [nombreeccion]}}

    
asked by Jcastillovnz 06.11.2017 в 21:30
source

1 answer

1

What you have to do is a query with query builder as follows:

$records = DB::table('semestre')
             ->join('seccion', 'seccion.semestre_id', '=', 'semestre.id')
             ->paginate(5);

This will bring you all the semester records and you can access the property nombresección

Another way to do this is through the Eloquent relationships , in your semester model you can create the next relationship:

If it's 1 to many, it's:

function secciones()
{
    return $this->hasMany('Ruta de tu modelo de section', 'semestre_id');
}

If it's a 1 to 1 ratio:

function seccion()
{
    return $this->hasOne('Ruta de tu modelo de sección', 'semestre_id');
}

With this previous function, what you do is that you consult a semester record and you can directly access your relationship in the following way, taking the 1 to 1 relationship as an example:

$semestre = Semestre::find('ID del semestre');
$nombre_seccion = $semestre->seccion->nombreseccion;

I hope it's your help

    
answered by 06.11.2017 / 23:03
source