如何在Laravel eloquent中编写子查询

时间:2017-10-24 09:20:43

标签: laravel eloquent

以下是我的MySQL查询

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

我想用laravel eloquent写的。 你能帮我么。因为我是新手。

2 个答案:

答案 0 :(得分:2)

嗯,有几种方法可以做到这一点。

使用DB facade

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

使用雄辩和原始查询

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

使用Eloquent和DB facade

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

答案 1 :(得分:1)

尚未测试过,但您可以尝试一下:

(假设您的相应模型称为public void printTitles(){ Date todayDate = new Date(); System.out.printf("_______________________________________"); System.out.printf("\n\t\t\tInvoice 1"); System.out.printf("\n\t\t\t\t%td-%<tb-%<tY", todayDate); } public void printHeaders(){ System.out.printf("\n---------------------------------------"); System.out.printf("\n| ID |\t\t\tDESC\t\t|\tAMT\t |"); System.out.printf("\n---------------------------------------"); } public void printRows(String id, String desc, int fee) { System.out.printf("\n| %s | %.20s| %,8d|", id, desc, fee); System.out.printf("\n---------------------------------------"); } public void printResult() { System.out.printf("\n|\t Sub Total\t\t %,8d|",subTotal); System.out.printf("\n---------------------------------------"); System.out.printf("\n|\t Tax(5%%)\t\t\t\t %,8d|", tax); System.out.printf("\n---------------------------------------"); System.out.printf("\n|\t Total\t\t\t\t %,4d|", total); System.out.printf("\n---------------------------------------"); System.out.printf("\n\t\t\t\tTHANK YOU!"); System.out.printf("\n_______________________________________"); }

MemberMeasurementRecords