10 months ago

Getting all records which relationship doesn't have a specific value in Laravel 5.5.

Posted 10 months ago by Toughoj

I’ve got 3 related Models :

  1. Question.
  2. Answer.
  3. User

Each question can have many answers so it can be answered by many users.

I need to filter questions according to 2 criteria:

  1. get all question which was answered by a specific user.
  2. get all questions which was NOT answered by a specific user.

I was able to hit the first criteria by the following :

Question::whereHas(‘Answers’, function ($query) { $query→where(‘user_id’, $user_id); });

BUT how can I satisfy the second criteria using “whereHas”? I tried :

Question::whereHas(‘Answers’, function ($query) { $query→where(‘user_id’, ’!=’ ,$user_id); });

but the above query is wrong since multiple users can answer the same question .So if any question was answered by multiple users including the specific user they will be fetched as well, which is not what I am going for.

Thank you in advance for your help :)

Please sign in or create an account to participate in this conversation.