在Laravel 5 Eloquent中获取原始SQL查询的结果

时间:2022-05-26 08:02:20

I need help to build a Laravel query from my raw SQL Query. I tried many way and did not find my Luck. Can anybody help me? My Raw SQL code is given bellow.

我需要帮助从我的原始SQL查询构建一个Laravel查询。我尝试了很多方法,没有找到我的运气。有谁能够帮我?我的Raw SQL代码如下所示。

SELECT exams. * , count( question_details.exam_id ) AS qus_enter
FROM exams
INNER JOIN question_details ON exams.id = question_details.exam_id GROUP BY exams.id

This is what I've tried:

这就是我尝试过的:

$examListsID = DB::table('exams')
                 ->join('question_details', function($join) {
                     $join->on('exams.id', '=', 'question_details.exam_id as qus_enter');
                 })
                 ->whereraw('count(qus_enter) = exams.total_question')
                 ->select('exams.id as examID','qus_enter','exams.total_question')
                 ->count('qus_enter')
                 ->groupby('exams.id')
                 ->get();

$examLists = Addexam::where('id','=',$examListsID->examID)

And I Get this Error:

我收到此错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as qus_enter where count(qus_enter) = exams.total_question' at line 1 (SQL: select count(qus_enter) as aggregate from exams inner join question_details on exams.id = question_details.exam_id as qus_enter where count(qus_enter) = exams.total_question)

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以获得正确的语法,以便在第1行使用'qus_enter where count(qus_enter)= exams.total_question'(SQL:select count(qus_enter)作为考试中的聚合内部联接在考试中加入问题_details .id = question_details.exam_id为qus_enter,其中count(qus_enter)= exams.total_question)

1 个解决方案

#1


$result = DB::table('exams')->join('question_details','exams.id','=','question_details.exam_id')->select([
  exams.*,
  DB::raw('count( question_details.exam_id ) AS qus_enter')
])->GroupBy('exams.id')->get()

Hope this helps

希望这可以帮助

#1


$result = DB::table('exams')->join('question_details','exams.id','=','question_details.exam_id')->select([
  exams.*,
  DB::raw('count( question_details.exam_id ) AS qus_enter')
])->GroupBy('exams.id')->get()

Hope this helps

希望这可以帮助