I want to understand why this solution works
Hello. I am developing a large application and using Eloquent as much as I can but there are situations where Eloquent does not work or I can't figure out the right way to use it, as is this case I am showing here.
What I want to know is how come this solution using joins and raw SQL statements is working, because I just did that quickly and I want to research a better way to approach this problem in the future.
The objective is to have a table filled with the common data from all the other tables. I did left all the comments in so you can have a better understanding what this code was like.
As you can notice the previous code were way more better and readable using Eloquent and the merge method, but unfortunately the merge method does overwrite all the relations for some reason.
Again, just look at this ugly code and let me know what is the reason this works and if you have a better way to tackle the problem I will be glad to hear.
Thank you in advance and now here is the code:
public function anyDataPagar() {
//$despesas = DespesaOperacional::where('status','<>','PAGO')->with('user')->with('crt')->with('moeda')->get();
//$estadias = PagamentoEstadia::where('status','<>','PAGO')->with('estadia')->with('usuario')->get();
//$fretes = PagamentoFrete::where('status','<>','PAGO')->with('frete')->with('usuario')->get();
// $contas = ContaFilial::where('status','<>','PAGO')->with('operacao')->with('moeda')->with('user')->get();
// $adiantamentos = Adiantamento::where('status','<>','PAGO')->with('moeda')->with('usuario')->get();
//$despesasOperacionaisFrota = DespesaOperacionalFrota::where('status','<>','PAGO')->with('moeda')->with('usuario')->get();
//$despesasViagemFrota = DespesaViagemFrota::where('status','<>','PAGO')->with('moeda')->with('usuario')->get();
/**
* Utilizar merge neste caso não está funcionando porque as colunas têm nomes iguais e o merge está sobreescrevendo.
* Foi utilizado o operador UNION que exige que os resultados das consultas tenham o mesmo número de colunas.
* Assim, é utilizado DB::raw para retornar colunas nulas quando as mesmas não existirem na tabela de origem.
* Por algum motivo que ainda precisa de mais pesquisa, utilizar with() com o nome da coluna de origem (neste caso, a coluna user_id) está funcionando,
* ao invés do nome da relação definida na classe Model (no caso, usuario_id).
*
* TODO: pesquisar esse comportamento
**/
$despesas = DespesaOperacional::where('status','<>','PAGO')
//->with('user')
//->with('crt')
// ->with('moeda')
// ->with('estadia')
->select('id','created_at','moeda_id','valor','taxa','valor_usd','user_id','hash','crt_id',DB::raw('null as tipo'),DB::raw('null as crt_numero'));
$estadias = PagamentoEstadia::where('status','<>','PAGO')
//->with('user')
->join('estadias','pagamentos_estadias.estadia_id','=','estadias.id')
->select('pagamentos_estadias.id','pagamentos_estadias.created_at','moeda_id','valor','taxa','valor_usd','pagamentos_estadias.usuario_id','hash','crt_id',DB::raw('null as tipo'),DB::raw('null as crt_numero'));
$fretes = PagamentoFrete::where('status','<>','PAGO')
->join('fretes','pagamentos_fretes.frete_id','=','fretes.id')
->select('pagamentos_fretes.id','pagamentos_fretes.created_at','moeda_id','valor','taxa','valor_usd','pagamentos_fretes.usuario_id','hash','crt_id',DB::raw('null as tipo'),DB::raw('null as crt_numero'));
$contas = ContaFilial::where('status','<>','PAGO')
->join('operacoes_caixa','contas_filiais.operacao_id','=','operacoes_caixa.id')
->select('contas_filiais.id','contas_filiais.created_at','moeda_id','valor','taxa','valor_usd','contas_filiais.user_id','hash',DB::raw('null as crt_id'),'operacoes_caixa.tipo',DB::raw('null as crt_numero'));
$adiantamentos = Adiantamento::where('status','<>','PAGO')
->select('id','created_at','moeda_id','valor','taxa','valor_usd','usuario_id','hash',DB::raw('null as crt_id'),DB::raw('null as tipo'),'crt_numero');
$despesasOperacionaisFrota = DespesaOperacionalFrota::where('status','<>','PAGO')
// ->with('moeda')
// ->with('user')
->select('id','created_at','moeda_id','valor','taxa','valor_usd','usuario_id','hash',DB::raw('null as crt_id'),DB::raw('null as tipo'),DB::raw('null as crt_numero'));
$despesasViagemFrota = DespesaViagemFrota::where('status','<>','PAGO')
// ->with('moeda')
// ->with('user')
->select('id','created_at','moeda_id','valor','taxa','valor_usd','usuario_id','hash',DB::raw('null as crt_id'),DB::raw('null as tipo'),DB::raw('null as crt_numero'));
$todasDespesas = $despesas
->union($estadias)
->union($fretes)
->union($contas)
->union($adiantamentos)
->union($despesasOperacionaisFrota)
->union($despesasViagemFrota)
->with('user')
->with('crt')
->with('moeda')
->get();
// dd($todasDespesas);
// $faturasFiscais = Faturamento::where('cliente_id',$cliente_id)->where('status','<>','CANCELADO')->with('moeda')->with('recibos')->with('crt')->get();
// $faturasNaoFiscais = FaturamentoLivre::where('cliente_id',$cliente_id)->where('status','<>','CANCELADO')->with('moeda')->witH('crt')->get();
// $all = $despesas->merge($estadias);
// $all = $all->merge($fretes);
// $all = $all->merge($contas);
// $all = $all->merge($adiantamentos);
// $all = $all->merge($despesasViagemFrota);
// $all = $all->merge($despesasOperacionaisFrota);
//dd($all);
return Datatables::of($todasDespesas)
->editColumn('created_at', function ($despesa) {
return $despesa->created_at != null ? $despesa->created_at->format('d/m/Y') : '-';
})
->addColumn('moeda', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return $despesa->moeda->simbolo;
break;
case 2:
return $despesa->moeda->simbolo;
break;
case 3:
return $despesa->moeda->simbolo;
break;
case 4:
return $despesa->moeda->simbolo;
break;
case 7:
return $despesa->moeda->simbolo;
break;
case 8:
return $despesa->moeda->simbolo;
break;
case 9:
return $despesa->moeda->simbolo;
break;
default:
return 0;
break;
}
})
->editColumn('valor', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 2:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 3:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 4:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 7:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 8:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
case 9:
return number_format($despesa->valor,$despesa->moeda->casas_decimais,',','.');
break;
default:
return 0;
break;
}
})
->editColumn('taxa', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 2:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 3:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 4:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 7:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 8:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
case 9:
return number_format($despesa->taxa,$despesa->moeda->casas_decimais,',','.');
break;
default:
return 0;
break;
}
})
->editColumn('valor_usd', function ($despesa) {
return number_format($despesa->valor_usd,2,',','.');
})
->addColumn('tipo', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return 'Despesa Operacional';
break;
case 2:
return 'Estadia';
break;
case 3:
return 'Carta Frete';
break;
case 4:
return $despesa->tipo;
break;
case 7:
return 'Adiantamento Motorista';
break;
case 8:
return 'Despesa de Viagem de Frota';
break;
case 9:
return 'Despesa Operacional de Frota';
break;
default:
return 'Sem Tipo';
break;
}
})
->addColumn('crt', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return $despesa->crt != null ? $despesa->crt->number : ' - ';
break;
case 2:
return $despesa->crt != null ? $despesa->crt->number : ' - ';
break;
case 3:
return $despesa->crt != null ? $despesa->crt->number : ' - ';
break;
case 7:
return ($despesa->crt_numero != null && $despesa->crt_numero != null) ? $despesa->crt_numero : ' - ';
break;
default:
return ' - ';
break;
}
})
->addColumn('usuario', function ($despesa) {
switch ($despesa->hash[0]) {
case 1:
return $despesa->user->name;
break;
case 2:
case 3:
return $despesa->user->name;
break;
case 4:
return $despesa->user->name;
break;
case 7:
return $despesa->user->name;
break;
case 8:
return $despesa->user->name;
break;
case 9:
return $despesa->user->name;
break;
default:
return 'Sem Usuário';
break;
}
})
->addColumn('action', function ($despesa) {
$actions = '';
switch ($despesa->hash[0]) {
case 1:
$actions .= '<a href="/admin/cartas-frete/despesas/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 2:
$actions .= '<a href="/admin/cartas-frete/pagamentos-estadias/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 3:
$actions .= '<a href="/admin/cartas-frete/pagamentos-fretes/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 4:
$actions .= '<a href="/admin/contas-filial/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 7:
$actions .= '<a href="/admin/frotas/adiantamentos/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 8:
$actions .= '<a href="/admin/frotas/despesas-viagem/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
case 9:
$actions .= '<a href="/admin/frotas/despesas-operacionais/emitir/'.$despesa->id.'" class="btn btn-xs blue" target="_blank"><i class="fa fa-eye"></i> Visualizar Recibo</a>';
break;
default:
$actions .= '<button class="btn btn-xs blue" disabled><i class="fa fa-eye"></i> Visualizar Recibo</button>';
break;
}
$actions .= '<form action="/admin/financeiro-matriz/contas-pagar/baixar/'.$despesa->hash.'" method="post" style="display:inline;"><input type="hidden" name="_token" value="'.csrf_token().'"><button class="btn btn-xs green-jungle"><i class="fa fa-money"></i> Baixar</button></form>';
return $actions;
})
->make(true);
}
Please or to participate in this conversation.