-1

I tried distinct before but somehow my query won't select the last comment. He always select the oldest comment. Then i tried it with groupBy instead of distinct. But this 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 someone can explain me why this won't work.

Laerte
  • 7,013
  • 3
  • 32
  • 50
Smokegun
  • 81
  • 2
  • 14

2 Answers2

1

Errors found so far

  1. groupBy is not needed
  2. Your join statement join('topics', 'comments.topic_id', '=', 'comments.id') should be joining columns in table comments and 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') is handy for orderBy('comments.id', 'desc')

UPDATE

To get the latest comment for at most 5 recently updated topics, try this

\App\Comment::select('comments.user_id', 'topics.id', 'topics.name')
    ->from(DB::raw("(select * from comments where removed = 0 order by id desc) as comments"))
    ->join('topics', 'comments.topic_id', 'topics.id')
    ->whereIn('topics.cat_id', $cats)
    ->where('topics.removed', false)
    ->groupBy('topics.id')
    ->limit(5)
    ->get();
Victor Anuebunwa
  • 2,553
  • 2
  • 24
  • 34
0

Try to use whereHas. You should do something like this:

\App\Comment::where('removed', false)
            ->whereHas('topic', function($q) use ($cats) {
                $q->where('removed', false)
                  ->whereIn('cat_id', $cats);
            })
            ->limit(5)
            ->orderBy('id', 'desc')->get();

To achieve this, you must have the relations established by functions, such as topics (ie: hasMany) in Comment model.

halfer
  • 19,824
  • 17
  • 99
  • 186
Laerte
  • 7,013
  • 3
  • 32
  • 50
  • Call to undefined method Illuminate\Database\Query\Builder::topics() the relations are there commet has a belongs to topic and topic has a hasmany comments – Smokegun Jul 25 '17 at 19:36
  • If comment belongs to topic, try only `whereHas('topic', function($q) {`. – Laerte Jul 25 '17 at 19:53
  • whereIn('topics.cat_id', $cats) topics.cat_id doesn;t exist there because join isn;t use and if i add whereIn to the $q it can't reach the variable $cats? – Smokegun Jul 25 '17 at 19:56
  • I've edited the answer, you must use `use ($cats)` to make it available in the function. Try it again, please – Laerte Jul 25 '17 at 20:09