2014-11-04 32 views
0

表:問題(ID,問題),回答問題(ID,question_id,答案)相關表中獲取與查詢生成器

一個問題有很多答案

我怎樣才能從一個表中的數據(例如,問題)以及來自另一個表(答案)的所有相關數據,僅使用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(); 

這是我到目前爲止,但它似乎並沒有提供完全我想要的數據結構的方式。

enter image description here

回答

0

表:問題(ID,問題),回答問題(ID,question_id,答案)

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

運行這一點,如果它仍然無法正常工作,給我們的一個toSql()查詢構建器的SQL。

你必須更具體地說明你想要的數據結構。如果PHP更復雜,它可能需要更多的操作。

在你的問題類
+0

您提供的代碼只是爲每個問題返回1個答案。但它假設爲每個問題提供多個答案 – 2014-11-04 22:20:40

+0

這不是Laravel或查詢構建器的問題,而是您在MySQL中構建數據的方式的問題。 – 2014-11-04 22:39:56

0

所以,你必須添加此

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 

編輯:所以你沒有使用雄辯。只有一個問題,爲什麼在你的選擇你得到同一列兩倍? 'questions.id'和'answers.question_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(); 
+0

他沒有使用雄辯。 – 2014-11-04 22:39:26