loveioielws
loveioielws

Reputation: 23

laravel subquery whereIn and maximum value

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?

Upvotes: 2

Views: 2570

Answers (1)

Mark Davidson
Mark Davidson

Reputation: 5513

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")

Upvotes: 4

Related Questions