2015-05-04 98 views
0

我需要帮助,从我的原始SQL查询构建Laravel查询。我尝试了很多方法,没有找到我的运气。有谁能够帮助我?我的原始SQL代码如下。在Laravel 5中获取原始SQL查询的结果Eloquent

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 

这是我已经试过:

$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) 

,我得到这个错误:

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)

+0

那么请让我们了解您其实试过 – lukasgeiter

+0

我有两个表一是'考试'和'问题tion_details'。在我的“考试”表中,我设置了考试的总体问题,并在我的'question_details'中输入了与'exam_id'相关的问题。 我只想加载那个在'question_details'表中插入所有问题的考试。 –

+0

我的意思是我希望你用Laravel查询代码更新你的答案(即使它不工作) – lukasgeiter

回答

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() 

希望这有助于