Rubberduck1337106092
Rubberduck1337106092

Reputation: 1344

How to use a where query inside a laravel relationship?

Hello i have a CommentRetours table which connects the retours to the comments.

The DB:

enter image description here

I need to display all comments for a user and return that to the view.

I now have this query:

    $comments = CommentRetours::with(['comments' => function($q) {
        $q->where('user_id',Auth()->user()->id);
    }])->get();

This return NULL..

The user_id is inside the comments table.

As constructure example i will add this:

enter image description here

What am i doing wrong?

Upvotes: 0

Views: 1250

Answers (2)

AntoineB
AntoineB

Reputation: 4694

The question is quite old but the solution adopted by OP being less than ideal, here is what he probably should have done:

$comments = CommentRetours::whereHas(['comments' => function($q) {
    $q->where('user_id', Auth::id());
}])->with('comments')->get();

whereHas checks if the CommentRetours have some comments that match the condition.

I also replaced Auth()->user()->id by Auth::id().

Upvotes: 2

Rubberduck1337106092
Rubberduck1337106092

Reputation: 1344

I fixed it by adding user_id to the CommentRetours table, now I wont have to query inside the other relationship.

I can just see user_id directly inside the table.

Upvotes: 0

Related Questions