1

I need help to create my query. I created the following query in SQL

SELECT id_funcionario, MAX(created_at) from irs GROUP by id_funcionario

I try to switch to Larevel but I'm wrong and I can't put the groupby

    $irs = irs::join('utilizadors','utilizadors.id','=', 'irs.id_funcionario')
    ->MAX('created_at')
   
    ->get([ 'utilizadors.id', 'utilizadors.nome', 'irs.id', 'irs.id_funcionario','irs.created_at', 'irs.dependentes', 'irs.titulares_rendimento', 'irs.situacoes_especiais']);
    return view('irs-total', ['itens' => $irs]);
1
  • Why are you calling ::join() when your original SQL doesn't have any kind of JOIN ... clause? I would expect the correct syntax would be something like irs::select(['id_funcionario', DB::raw('MAX(created_at)'])->groupBy('id_funcionario')->get(). If you need to verify, replace ->get() with ->toSql() to see the generated SQL. Commented Apr 4, 2022 at 20:49

1 Answer 1

1

Try this:

use Illuminate\Support\Facades\DB;
 $irs = DB::table('irs')
             ->join('utilizadors','utilizadors.id','=', 'irs.id_funcionario')
             ->select(DB::raw('irs.created_at'), 'utilizadors.id', 
                'utilizadors.nome', 'irs.id', 'irs.id_funcionario','irs.created_at', 
                'irs.dependentes', 'irs.titulares_rendimento', 
                'irs.situacoes_especiais')
             // add your groupBy data
             ->groupBy('')
             ->get();
Sign up to request clarification or add additional context in comments.

3 Comments

Why DB::table('irs')? They have a model irs.
I think it's the first table he's trying to join with utilizadors
You're missing the point of that comment; if they have a Model irs, you should encourage using it instead of DB::table('irs'), so irs::join(...)->select(...) and so on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.