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 FeatureVote
s.
I want to execute a query that:
Excludes users’ own feature requests:
$f = FeatureRequest::where('user_id', '!=', Auth::user()->id)->get();
…and Excludes FeatureRequest
s 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 FeatureRequest
s 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
You can use
whereHas()
like following:You can consider doing like the below: