'Is there a way to get Collection of a model and get only objects whose relationship rows exists?

I have three models User, Post and Comment

User
  -id
Post
  -user_id
Comment
  -post_id

My table has issues, for example, some posts are not there or some user rows are not there.

How can I be able to get only comments that have a post_id which exists and it also has a user_id of the user which exists using a scope most preferably global scope?



Solution 1:[1]

I recommend that you first try to resolve this anomaly what happened in the database. You could achieve it using nullable foreign id, and foreign key constraints.

If you use foreing key constraint it shall not happen that a model connected to a not existing model. You could set it null, all the foreign ids which does not exists, in the parent database.

Alternatively you could use this code:

   Comment::whereHas('post', function($q){
    $q->has('user');
   })->get();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mátyás Gr?ger