我的数据库中有几张表:
我的目标是加载给定调查中的所有问题,并按特定顺序对其进行排序。但是,我似乎无法做到这一点。我已经尝试过以下查询的许多不同变体,而且它总是几乎"有效,但有些问题会出现问题。我对SQL不好,所以如果我错过了一些明显的东西,那就很抱歉。
$questions = Survey::find($survey->id)->questions()
->join('orders as o', 'o.question_id', '=', 'questions.id')
->orderBy('o.order', 'desc')
->groupBy('questions.id')
->get();
我然后将它们添加到数组并在视图中调用它们:
($survey_questions[$survey->id] as $q)
更新
嗯......我不认为这可能是最好的解决方案,(所以我没有把它标记为答案),但至少它有效。为了正确地订购,我必须首先选择调查并从那里建立连接,然后在我的视图中创建一个单独的question_id => answers
数组来循环...它可以工作,但我很确定这不是理想的。
$survey_responses = array();
$survey_questions = array();
$question_answers = array();
foreach($surveys as $survey) {
$responses = $survey->responses()->where('survey_id', '=', $survey->id)->count();
$survey_responses[$survey->id] = $responses;
$questions = Order::where('survey_id', '=', $survey->id)
->join('questions as q', 'q.id', '=', 'orders.question_id')
->select('q.*') // add anything you need here
->orderByRaw('orders.order asc')
->groupBy('q.id')
->get();
$survey_questions[$survey->id] = $questions;
//make question_id => answers array because I can't figure out the damn select query
foreach($survey->questions as $question) {
foreach($question->answers as $answer) {
$question_answers[$question->id][$answer->id] = $answer->answer;
}
}
}
答案 0 :(得分:0)
使用eloquent时,如果使用select
,则需要指定要joins
的列。否则ids
(可能还有其他列)将被相关表的值覆盖,结果是错误的。
$questions = Survey::find($survey->id)->questions()
->join('orders as o', 'o.question_id', '=', 'questions.id')
->orderBy('o.order', 'desc')
->groupBy('questions.id')
->select('questions.*') // add anything you need here
->get();