-1

I have 2 tables (posts, revisions), and there is a relationship between them
A post has many revisions (One to Many relationship)
Revisions table has a column called status (approved or rejected)
Now, I want to select all posts, if its latest revision is approved
I tried a lot of methods, but I could get the posts that have an approved status


Update

I found a good solution in that reply

https://stackoverflow.com/a/53120558/9500574

user9500574
  • 142
  • 1
  • 11

1 Answers1

2
Post::with([ 'revisions' => function($query) {
   $query->orderBy('created_at', 'desc')->where('status', 'approved')->limit(1);   
}])->get()->filter(function($item) {
   return $item->revisions->count() > 0;
});

The collection will contain only those posts with approved revisions.

nakov
  • 13,938
  • 12
  • 60
  • 110
  • Thanks a lot, Is there any way to filter the results directly during the query, without using the method of **filter** after getting the results – user9500574 Nov 06 '18 at 23:42
  • There is no way without filtering, because Posts always exists, even without revision. – nakov Nov 06 '18 at 23:44