iamafasha
iamafasha

Reputation: 794

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?

Upvotes: 0

Views: 81

Answers (2)

Adam
Adam

Reputation: 29079

Assuming you have set up the relationships in the models, you can get them using the whereHas method:

$commentsWithPostWhichHaveAUser = Comment::whereHas('Post', function($query){
    $query->has('User');
});

Upvotes: 1

Mátyás Grőger
Mátyás Grőger

Reputation: 1692

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();

Upvotes: 1

Related Questions