andersb
5 months ago

Conditional filtering on related model

Posted 5 months ago by andersb

I have two models A and B with a 1:n relationship and would like to find all B records where the associated A record meets a condition on B.

Example:

Get all comments that were created after a month of the original post being created.

It's possible for a single post to get all the comments meeting the condition using something like:

$post->comments()->whereDate('created_at', '>', $post->created_at->addMonth());

But how do you get all comments (for all posts) that were created after a month of the post being created?

Secondly, how do you get all posts that has a least one comment created after a month of the post being created?

Thanks so much.

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