Saturday, April 15, 2017

Retrieve the author of the last comments

I want to retrieve the name of the person who posted the last comment in a topic for a forum. This is what I do at PhpMyAdmin and that works so I get the right values:

select commentaires.auteur 
from commentaires inner join sujets on commentaires.sujet_id = sujets.id
where commentaires.id = (
    select max(commentaires.id)
    from commentaires inner join sujets on commentaires.sujet_id = sujets.id
    where sujets.id = 12
);

I thought using QueryBuilder to retrieve the values I wanted but I realize it's quite complex .. Here is one of my essays:

DB::table('commentaires')->join('sujets', 
'sujets.id','=','commentaires.sujet_id')  
->where(['commentaires.id' => DB::raw('max(commentaires.id')])
->where('sujets.id','=', $unSujet->id)
->value('commentaires.auteur')

Or would you have a simpler idea? Thank you in advance for your help.



via B.Rousseaux

Advertisement