Ad

Laravel Subquery WhereIn And Maximum Value

- 1 answer

i'm newbie to laravel and mysql

mysql query is

select * from table where id in ( select max(id) from table group by thread_id)

my table is

id  thread_id
1    45a7
2    123c
3    45a7
4    d056
5    123c

output for mysql table is

id   thread_id
3    45a7
5    123c
4    d056

Here i tried to transfer my mysql query to laravel as below

MODEL::whereIn('id', function($query){ $query->groupBy('thread_id')})->get();

what's i'm doing wrong?

Ad

Answer

The below should match your query

Model::whereIn('id', function($query) { 
    $query->selectRaw('max(id)')->from('table')->groupBy('thread_id'); 
})->toSql();

this will output

select * from "table" where "id" in (select max(id) from table group by "thread_id")
Ad
source: stackoverflow.com
Ad