0

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.

3
  • Have you created models for each table? Commented Oct 24, 2017 at 9:23
  • @Suraj yes I have created models for each table Commented Oct 24, 2017 at 9:25
  • Answering this is entirely dependant on what you named your models. Would you share them in your question. Commented Oct 24, 2017 at 9:36

2 Answers 2

2

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'));
Sign up to request clarification or add additional context in comments.

Comments

1

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');

1 Comment

using subquery here is great

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.