php - Laravel query doesn't want to select last one -


i tried distinct before somehow query won't select last comment. select oldest comment. tried groupby instead of distinct. won't work either.

my current query:

\app\comment::limit(5)->groupby('comments.id')             ->orderby('comments.id', 'desc')             ->join('topics', 'comments.topic_id', '=', 'comments.id')             ->select('comments.user_id', 'topics.id', 'topics.name')             ->wherein('topics.cat_id', $cats)             ->where([['comments.removed', '=', false],['topics.removed', '=', false]])             ->get(); 

it's pretty long. hopfully can explain me why won't work.

errors found far

  1. groupby not needed
  2. your join statement join('topics', 'comments.topic_id', '=', 'comments.id') should joining columns in table comments , topics

fix

\app\comment::select('comments.user_id', 'topics.id', 'topics.name')     ->join('topics', 'comments.topic_id', 'topics.id')     ->wherein('topics.cat_id', $cats)     ->where('comments.removed', false)     ->where('topics.removed', false)     ->latest('comments.id')     ->limit(5)     ->get(); 

ps: latest('comments.id') handy orderby('comments.id', 'desc')

update

to latest comment @ 5 updated topics, try this

\app\comment::select('comments.user_id', 'topics.id', 'topics.name')     ->from(db::raw("(select * comments removed = 0 order id desc) comments"))     ->join('topics', 'comments.topic_id', 'topics.id')     ->wherein('topics.cat_id', $cats)     ->where('topics.removed', false)     ->groupby('topics.id')     ->limit(5)     ->get(); 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -