laravel 分组查询 获取最新一条数据 子查询

期望实现

SELECT * FROM
	(SELECT a.* FROM app AS a LEFT JOIN su s ON a.user_id = s.user_id AND a.school_id = s.school_id WHERE a.user_id = 1 ORDER BY a.id desc ) AS c 
	group by school_id

laravel 模型 查询

$sql = Apply::query()->from('app as a')
            ->join('su as s', 'a.school_id', '=', 's.school_id', 'left')
            ->orderByDesc('a.id')->select(['a.*']);
$data  =  Apply::query()
		->from(DB::raw("({$sql->toSql()}) as sub"))
		->where('user_id', '=', 1)
		->orderByDesc('id')
		->groupBy('school_id')
		->get(['*', 'school_id as school_str']);

结果示例

[
    {
        "id": 6,
        "status": "0",
        "school_str": 5
    },
    {
        "id": 3,
        "status": "0",
        "school_str": 4
    },
    {
        "id": 2,
        "status": "0",
        "school_str": 3
    }
]

你可能感兴趣的:(laravel查询)