Sorting the results of a query - Laravel 5.1

1

I currently have a code that receives data from the registered companies and for each company it lists the reports of them as follows:

@foreach($empresas as $empresa) // Recebe as empresas
   @foreach($empresa->CgrtInfo as $relatorio) // Busca Relatórios da empresa
      <tr>
         <td>{{ $relatorio->id }}</td>
         <td>{{ $relatorio->Empresa->razao_social }}</td>
      </tr>
   @endforeach
@endforeach

I'm doing the search on Controller as follows:

$empresas = $cliente->Empresa()->where('razao_social', 'ILIKE', '%'.$busca.'%')->paginate(10);

CgrtInfo Table (Reporting Information):

$table->increments('id');
$table->integer('id_empresa')->unsigned();//Foreign key
$table->integer('id_cliente')->unsigned();//Foreign key

Company Table:

$table->increments('id');
$table->integer('id_cliente')->unsigned();//Foreign key
$table->string('razao_social', 128);

Model CgrtInfo:

public function Empresa(){ 
   return $this->belongsTo('SIST\Models\Client\Empresa', 'id_empresa'); 
}

Model Company:

public function CgrtInfo(){ 
   return $this->hasMany('SIST\Models\Client\Cgrt\CgrtInfo', 'id_empresa');
}

But in this way the id of the reports ends up being out of order, because if report # 10 was from company 1, and report 5 was from company 2, it ends up being 10 in front of 5.

  

"Oh, and why do not you go directly through the reports?"

I honestly could not, because when the listing is made based on a search, I have to search for the corporate name of the company, and I do not have and did not think it necessary to put this information in the report model, but if there is no way .. .

    
asked by anonymous 29.01.2016 / 13:53

1 answer

1

You can bring all reports in SELECT :

<?php 
    use DB;

    ...

    $relatorios = DB::table('CgrtInfo')
                      ->join('empresa', 'empresa.id', '=', 'CgrtInfo.id_empresa')
                      ->orderBy('empresa.id')
                      ->where('razao_social', 'ILIKE', '%'.$busca.'%')
                      ->paginate(10);

    ?>
    
29.01.2016 / 14:19