【问题标题】:Join Query Sort by Related Table in Eloquent Not Quite Working在 Eloquent 中加入查询按相关表排序不太工作
【发布时间】:2015-03-27 13:21:11
【问题描述】:

我的数据库中有几张表:

  • 问题 调查
  • 问题(有很多)-> 答案
  • 问题(有很多问题)-> *用于排序的订单
  • 调查(有很多)-> 订单 *用于对调查中的问题进行排序

我的目标是加载给定调查中的所有问题,并按特定顺序对它们进行排序。但是,我似乎无法完成这项工作。我已经尝试了以下查询的许多不同变体,它总是“几乎”有效,但有几个问题会出现问题。如果我遗漏了一些明显的东西,我对 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;
                }
            }
        }

【问题讨论】:

    标签: php mysql eloquent laravel-5


    【解决方案1】:

    使用 eloquent 时,如果使用 joins,则需要指定要使用 select 的列。否则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();
    

    【讨论】:

    • 嗯...我之前尝试过添加select(),但我只是再次这样做了。尽管如此,所有正确的信息都被提取出来了,实际上并不是由 o.order 排序的。
    • 然后显示相关表格
    猜你喜欢
    • 2020-02-25
    • 2019-09-16
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多