Home > front end >  Is there a way to get Collection of a model and get only objects whose relationship rows exists?
Is there a way to get Collection of a model and get only objects whose relationship rows exists?

Time:01-28

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?

CodePudding user response:

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

CodePudding user response:

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');
});
  •  Tags:  
  • Related