如何将以下查询转换为 Eloquent?

how to convert the following query into Eloquent?

我有一个查询可以正常工作但无法使用分页如何转换为 eloquent 以应用分页

$projects=DB::select("select * from projects INNER JOIN(select DISTINCT * from (SELECT project_id FROM district_group_project_users where user_id='$id' UNION ALL select id from projects where created_by='$id') as sub ) as sub on sub.project_id=projects.id;");

或者是否有任何其他选项可以为以下查询添加分页?谢谢

我假设您有一个名为 DistrictGroupProjectUser & Project 的模型。

$subQuery = DistrictGroupProjectUser::select('project_id')
                   ->where('user_id', $id)
                   ->union(Project::select('id')->where('created_by',$id))
                   ->distinct();

$projects = Project::joinSub($subQuery, 'sub', function ($join) {
                 $join->on('projects.id', '=', 'sub.projects_id');
            })->paginate(20);

基于laraveldocumentation