skip to Main Content

In Laravel, I have a model called FeatureRequest that can be voted on, thus creating a FeatureVote in a separate database table. A single FeatureRequest can have many FeatureVotes.

I want to execute a query that:

Excludes users’ own feature requests:

$f = FeatureRequest::where('user_id', '!=', Auth::user()->id)->get();

…and Excludes FeatureRequests they have not yet voted on.

FeatureRequest::whereDoesntHave(...)

I’m not sure how to do #2, because it seems whereDoesntHave will retrieve models that have zero instances of the related model. I just want to select FeatureRequests where there isn’t already a FeatureVote with user_id property equal to the authenticated user’s id.

ANSWER:

Thank you to Khang Tran for getting me half-way there! Here is what I settled on. It works perfectly:

$f = FeatureRequest::whereDoesntHave('feature_votes', function ($query){
        $query->where('user_id', '=', Auth::id());
    })->where('user_id', '!=', Auth::id())->get();

2

Answers


  1. You can use whereHas() like following:

    FeatureRequest::whereHas('votes', 
        function(Builder $query) {
            $query->where('user_id','=', Auth::id())
    }, '=', 0)
    
    Login or Signup to reply.
  2. You can consider doing like the below:

        FeatureRequest::whereHas('featureVotes')
           ->whereDoesntHave('featureVotes',function ($query) {
              $query->where('user_id','=', Auth::id())
           })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search