2016-09-03 176 views
1

用戶使用數據庫關係查詢 - >有許多問題 問題 - >有許多答案Laravel 5:

我想表明與最新回答一個用戶的問題信息,對每個問題

$questions = Question::select('id','user_id', 
      'title','video','status','created_at') 
      ->where('user_id','=',$user->id) 
      ->where('status','>=','2') 
      ->with([ 
       'user' => function($query){ 
        $query->select('id','name','picture'); 
       }, 
       'answers' => function($query){ 
        $query->select('id','question_id','user_id','answer','created_at',DB::raw('count(*) as answer_count')) 
        ->orderBy('created_at','desc')->first(); 

       }, 
      ])->get(); 

這裏每個問題我都沒有得到答案。我得到了用戶提交的所有問題的答案

你能幫助我嗎?如何把哪裏的問題ID爲答案

預期輸出:

User [id, name, and so on ] -> 
question [ 
    ['id', 'title' ..]->Answer['id','question_id',etc ], 
    ['id', 'title' ..]->Answer['id','question_id',etc ] 
] 

enter image description hereenter image description here

回答

0
$questions = Question::select('id','user_id','title','video','status','created_at')->with([ 
      'user' => function($query){ 
       $query->select('id','name','picture'); 
      } 
     ])->where('status','>=','2')->get(); 

     foreach($questions as $question) 
     { 
      $question_data[] = [ 
       'id' => $question->id, 
       'title' => $question->title, 
       'video' => $question->video, 
       'user_id' => $question->user_id, 
       'status' => $question->status, 
       'created_at' => $question->created_at->toDateTimeString(), 
       'thumbnail' => $question->thumbnail, 
       'user' => [ 
        'id' => $question->user->id, 
        'name' => $question->user->name, 
        'picture' => $question->user->picture 
       ], 
       'answers' => 
       $question->answers()->select('video','question_id','user_id','created_at','thumbnail') 
       ->with([ 
        'user' => function($query){ 
         $query->select('id','name','picture'); 
        } 
       ])->orderBy('created_at','desc')->first()]; 
     } 
1

你需要開始與他們的問題,獲取用戶和他們的答案,不與問題自己,以獲得預期的輸出:

$user = User::select('id','name','picture')->with([ 
      'questions' => function($query){ 
       $query->select('id','user_id','title','video','status','created_at'); 
       $query->where('status','>=','2'); 
      }, 
      'questions.answers' => function($query){ 
       $query->select('id','question_id','user_id','answer','created_at',DB::raw('count(*) as answer_count')); 
       $query->orderBy('created_at','desc')->first(); 

      }, 
     ])->findOrFail($user_id); 

現在,你應該能夠獲得通過給用戶提出的所有問題和最新的答案,他們有以下:

foreach($user->questions as $question) { 
    $answer = $question->answers; 
} 
+0

此查詢只顯示總體最新的應答(最新回答用戶的問題)。我想爲每個問題提供最新的答案 – Suba

+0

我不確定我的理解。上面的查詢將爲您提供用戶對象,給定用戶的所有問題以及他們每個問題的最新答案。這不是你需要的嗎? –

+0

是的。給定用戶的所有問題和他們每個問題的最新答案 – Suba