【问题标题】:Get from related tables with query builder使用查询生成器从相关表中获取
【发布时间】:2014-12-31 22:31:26
【问题描述】:

表格:问题(id、question)、答案(id、question_id、answer)

一个问题有很多答案

我如何仅使用 laravel 查询构建器从一个表(例如问题)及其所有相关数据从另一个表(答案)获取数据。

DB::table('questions')
                ->rightJoin('answers','questions.id', '=', 'answers.question_id')
                ->groupBy('questions.id')
                ->select('questions.question','answers.answer', 'questions.id', 'answers.question_id')
                ->get();

这是我目前所拥有的,但它似乎并没有给出我想要的数据结构方式。

【问题讨论】:

    标签: laravel query-builder


    【解决方案1】:

    表格:问题(id、question)、答案(id、question_id、answer)

    $query = DB::table('questions')
                 ->join('answers', 'questions.id', '=', 'answers.question_id')
                 ->select('questions.question','answers.answer', 'questions.id', 'answers.question_id')
                 ->get();
    

    运行它,如果它仍然不起作用,请给我们查询构建器的 SQL 的toSql()

    您必须更具体地说明您希望数据结构化的方式。如果更复杂,可能需要在 PHP 中进行更多操作。

    【讨论】:

    • 您提供的代码只为每个问题返回 1 个答案。但它假设每个问题都给出多个答案
    • 这不是 Laravel 或查询生成器的问题,而是您在 MySQL 中构建数据的方式的问题。
    【解决方案2】:

    所以在你的问题类中你必须添加这个

    public function answers(){
          return $this->hasMany('Answer');
    }
    

    如果你想知道你的问题的答案,你可以在你的刀片视图中做这样的事情

    @foreach($questions as $question)
        @foreach($question->answers as $answer)
           <td>{{ $question->question }}</td>
           <td>{{ $answer->answer }}</td>
           <td>{{ $answer->id }}</td>
           <td>{{ $question->id }}</td>
        @endforeach
    @endforeach
    

    编辑:所以你没有使用 eloquent .. 只是一个问题,为什么在你的选择中你得到两次相同的列? 'questions.id' 和 'answers.question_id' 将是相同的。如果您将 questions.id 更改为 answers.id

    DB::table('questions')
                    ->rightJoin('answers','questions.id', '=', 'answers.question_id')
                    ->groupBy('questions.id')
                    ->select('questions.question','answers.answer', 'answers.id', 'answers.question_id')
                    ->get();
    

    【讨论】:

    • 他没有使用 Eloquent。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2017-05-22
    • 2016-11-07
    • 2014-02-15
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多