Suba Suba - 2 months ago 9
PHP Question

Laravel 5 : database relation query using with

User -> Has many question
Question -> Has many answer

I want to show one user questions information with latest answer for each question

$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();


here I did not get answer for each question. I got answer for all questions submitted by the user

can you help me please? how to put where questions id for answer

Expected output:



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


enter image description here enter image description hereenter image description here

Answer
$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()];
        }