My aim of this data is to get the child latest class.
My table:
| id | child_id | class_id |
|----|----------|------------|
| 1 | 1 | 15 |
| 2 | 2 | 18 |
| 3 | 1 | 19 |
| 4 | 1 | 17 |
Expected result:
| id | child_id | class_id |
|----|----------|------------|
| 2 | 2 | 18 |
| 4 | 1 | 17 |
Actual result:
| id | child_id | class_id |
|----|----------|------------|
| 1 | 1 | 15 |
| 2 | 2 | 18 |
I am currently using Enrolment::orderBy('id', 'desc')->groupBy('child_id')->get();
. However it's not working correctly.
Try this code.
select * from table1
where id in (
select
Max(id) as t.id
from table1 as t
GROUP BY t.child_id ORDER BY t.id desc
)
This way, it could solve your problem:
SELECT * FROM `table_name` WHERE `id` IN (SELECT MAX(`id`) FROM `table_name` GROUP BY `child_id`)
You can use MAX
to show highest value
$response= Enrolment::groupBy('child_id')->get(['child_id', DB::raw('MAX(class_id) as class_ids')]);
and print result as
echo "<pre>";
print_r($response->toArray());
output will be
Array
(
[0] => Array
(
[child_id] => 1
[class_ids] => 19
)
[1] => Array
(
[child_id] => 2
[class_ids] => 18
)
)
Don't forget to import use DB;
in controller