5

I want to get all Items (topics) WITH their comments, if comments user_id = $id. I try something like this, but it isn't working. So if Item hasn't got any comment with user_id = $id, then I don't need this Item.

In DiscussionsItem model I have methode:

public function discussionsComments() {
    
    return $this->hasMany('DiscussionsComment', 'discussionsitem_id');
}

My query in controller is like this:

    $items = DiscussionsItem::whereBrandId($brand_id)
        ->whereBrandCountryId($country_id)
        ->with(['discussionsComments' => function($query) use ($id) {
            $query->where('user_id', '=', $id);
        }])
        ->whereHas('discussionsComments', function($query) use ($id) {
            $query->where('user_id', '=', $id);
        })
        ->with(['views' => function($query) use ($id) {
            $query->where('user_id', $id)->count();
        }])
        ->orderBy('created_at', 'DESC')->get();

My problem is that I get items with comments, where comments user_id != $id.

P.S. I need to take 5 comments, but I cant imagine how to do that, because ->take(5) in my eager load is not working.

miken32
  • 42,008
  • 16
  • 111
  • 154
user3921996
  • 149
  • 1
  • 1
  • 9
  • This is how you do it: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/ in MySQL – Jarek Tkaczyk Jan 21 '15 at 22:57
  • Does this answer your question? [Laravel eager loading with limit](https://stackoverflow.com/questions/33607088/laravel-eager-loading-with-limit) – miken32 Dec 07 '21 at 17:51

1 Answers1

-1

You can do a custom scope, or just limit the amount returned by your relation:

public function discussionsComments() {
    return $this->hasMany('DiscussionsComment', 'discussionsitem_id')
        ->latest()
        ->take(5);
 }
Robert
  • 5,703
  • 2
  • 31
  • 32