vendredi 2 septembre 2016

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 ]
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire