Laravel - Relationships using Eloquent

1

I'm trying to create a field relationship using eloquent de laravel, I currently have it working like this:

$empleos = Empleos::latest()->paginate(50);
return $empleos;

I return all jobs correctly, my problem is that there are fields that come from another external table, the logic would be the following:

$empleos = Empleos::latest()->paginate(50)->join('empresa','empresa.id''=','empreos.empresa');
return $empleos;

which is why he throws me an error that join is not identified: Method join does not exist.

Someone knows what I can do in this case, using eloquent.

JSON as it should be:

  

Current:

    data: [
    {
    id: 1,
    titulo: "Programador Android Jr.",
    empresa: 1,
    ...
    }]
  

As it should be:

data: [
        {
        id: 1,
        titulo: "Programador Android Jr.",
        empresa: "Empresa numero 1",
        ...
            }]

Structures table jobs Business table

    
asked by DoubleM 07.12.2018 в 00:57
source

1 answer

1

Simply reorder your query in this way

$empleos = Empleos::join('empresa','empresa.id''=','empreos.empresa')
                    ->latest()
                    ->paginate(50);
return $empleos;
  • That is, after calling the model Empleos , access the method join
  • After the latest() method that is similar to orderBy()
  • Finally page the results with paginate(50)
  • Remember to always end the query with ; because in your question you needed it
  • UPDATE

    To be able to indicate that instead of the id it shows you the name of the company you have this

    $empleos = Empleos::select("empleos.id", "empleos.titulo", "empresa.nombre")
                      ->join('empresa','empresa.id''=','empreos.empresa')
                            ->latest()
                            ->paginate(50);
        return $empleos;
    

    EXPLANATION

    Before the join you pass the method select() and indicate which columns and what table I need; in this way

    select("empleos.id", "empleos.titulo", "empresa.nombre")
    
      

    It only remains for you to verify and place, if necessary, the   name of the tables and columns; that is, if the table uses where you get > the title of employment has the column titulo use that, otherwise |   Place the appropriate name and so with each one

    second update

    As I understand your tables, a company has many jobs or jobs; for which your join seems to me to be badly raised; so it should be in this way assuming that your other model is called Company, if you do not put the right one

    $empleos = Empresa::select("empresa.id", "empleos.titulo", "empresa.nombre")
                      ->join('empleos','empresa.id', '=','empleos.empresa')
                            ->latest()
                            ->paginate(50);
    
        
    answered by 07.12.2018 в 01:07