【问题标题】:how to convert the following query into Eloquent?如何将以下查询转换为 Eloquent?
【发布时间】:2021-06-10 11:15:59
【问题描述】:

我有一个可以正常工作但无法分页的查询如何转换为 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;");

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

【问题讨论】:

    标签: laravel eloquent laravel-controller


    【解决方案1】:

    我想你有 Model 叫做 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);
    
    

    基于 laravel documentation

    【讨论】:

      猜你喜欢
      • 2022-07-29
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2013-01-08
      相关资源
      最近更新 更多