Gauri deshmukh
Gauri deshmukh

Reputation: 89

How to write sub query in Laravel eloquent

Following is my MySQL query

SELECT id 
FROM member_measurement_records 
WHERE date in (SELECT MAX(date) from member_measurement_records GROUP BY type)

Which I want to write using laravel eloquent. Can you please help me. As I am new to this.

Upvotes: 0

Views: 720

Answers (2)

Suraj
Suraj

Reputation: 2277

Well, there are several ways to do it.

Using DB facade

$data = DB::table('member_measurement_records')->where('date', DB::raw("(select max(`date`) from member_measurement_records GROUP BY type)"))->get();

Using eloquent and raw query

$data = MemberMeasurementRecords::whereRaw('date = (select max(`date`) from member_measurement_records GROUP BY type)')->get();

Using Eloquent and DB facade

$data = MemberMeasurementRecords::find(DB::table('member_measurement_records')->max('date')->groupBy('type'));

Upvotes: 2

Moritz Büttner
Moritz Büttner

Reputation: 904

Haven't tested it, but you can try it:

(It is assumend your corresponding model is called MemberMeasurementRecords)

MemberMeasurementRecords::whereIn('date', function ($query) {
            $query->max('date')->orderBy('type');
        })->get('id');

Upvotes: 1

Related Questions