I want to get all the elements (themes) With their comments, if the comments are user_id = $ id. I try something like this, but it does not work. Therefore, if an element has not received any comment with user_id = $ id, I do not need this element.
In the discussion, Model Name, I have a method:
public function discussionsComments() { return $this->hasMany('DiscussionsComment', 'discussionsitem_id'); }
My request in the controller is as follows:
$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 elements with comments, where user_id! = $ Id comments.
PS I need to accept 5 comments, but I canβt imagine how to do it, because β take (5) in my loaded download does not work.
I understood (working code):
$items = DiscussionsItem::whereBrandId($brand_id) ->whereBrandCountryId($country_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(); $items->each(function($topic) use ($id, 5){ $topic->comments = $topic->discussionsComments()->where('user_id', '=', $id)->get()->take(5); });