Laravel orderBy()在查询构建器中不使用groupBy()

时间:2017-10-11 13:58:07

标签: php laravel-5

我使用以下查询来显示按最近日期排序的用户测验结果。

$query = \DB::table('users_quiz_result');
    $query->join('users', 'users_quiz_result.user_id', '=', 'users.id');
    $query->join('user_profiles', 'users_quiz_result.user_id', '=', 'user_profiles.user_id');
    $query->join('quiz', 'users_quiz_result.quiz_id', '=', 'quiz.id');
    $query->select('users_quiz_result.id as quizresultid', 'users_quiz_result.invest_percent' ,'user_profiles.first_name','user_profiles.last_name', 'users.email AS email', 'quiz.name AS quizname', 'users_quiz_result.year AS quizyear',  'users_quiz_result.invest_percent AS investment','users_quiz_result.integration_percent AS integration', 'users_quiz_result.institution_percent AS institutionalisation', 'users_quiz_result.impact_percent AS impact', 'users_quiz_result.created_at AS quizdate');

    if(isset($_REQUEST['lastresult']) && trim($_REQUEST['lastresult'])==1)
    { 
        $query->groupBy('users_quiz_result.user_id');
    }
    if(isset($_REQUEST['username']) && trim($_REQUEST['username'])!='')
    {
        $query->where(function ($query) {
                $query->orwhere('user_profiles.first_name','LIKE', "%".trim($_REQUEST['username'])."%")
                      ->orwhere('user_profiles.last_name','LIKE', "%".trim($_REQUEST['username'])."%") 
                      ->orwhere(\DB::raw('CONCAT(user_profiles.first_name," ",user_profiles.last_name)'),'LIKE', "%".trim($_REQUEST['username'])."%") ; 
            });
    }

    if(isset($_REQUEST['useremail']) && trim($_REQUEST['useremail'])!='')
    {
        $query->where('users.email','LIKE', "%".trim($_REQUEST['useremail'])."%");
    }

    if(isset($_REQUEST['quizname']) && trim($_REQUEST['quizname'])!='')
    {
        $query->where('quiz.name','LIKE', "%".trim($_REQUEST['quizname'])."%");
    }

    if(isset($_REQUEST['quizname']) && trim($_REQUEST['quizname'])!='')
    {
        $query->where('quiz.name','LIKE', "%".trim($_REQUEST['quizname'])."%");
    }

    if(isset($_REQUEST['fromdate']) && trim($_REQUEST['fromdate'])!='')
    {
        $from = trim($_REQUEST['fromdate'])." 00:00:00";
        $to = trim($_REQUEST['fromdate'])." 23:59:59";

        if(isset($_REQUEST['todate']) && trim($_REQUEST['todate'])!='')
        {
            $to = trim($_REQUEST['todate'])." 23:59:59";
        }

        $query->whereBetween('users_quiz_result.created_at', [$from, $to]);
    }   

    $query->orderBy('users_quiz_result.created_at', 'DESC');
    $quizresult = $query->get();

我搜索了用户记录,如姓名,电子邮件,日期以及所有用户的最终结果。单个用户可以进行多个测验。

我使用以下查询显示所有用户的最后一条记录

if(isset($_REQUEST['lastresult']) && trim($_REQUEST['lastresult'])==1)
    { 
        $query->groupBy('users_quiz_result.user_id');
    }

使用groupBy显示单用户记录,但我无法根据日期获得最后一条记录。

我不知道如何解决这个问题请帮助我。提前谢谢。

0 个答案:

没有答案