Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Crazylife's avatar

How to filter result where need to depends on the calculation from relationship?

For example, I have a user, post, comment table.

I would like to calculate like 3 days average like and comment count for the post.

So in my post model will have something like this

protected $append = ['avg_like_count', 'avg_comment_count'];


public function getAvgLikeCountAttribute()
{
        return $this->comments->....conditions....->avg('like');
}

public function getAvgCommentCountAttribute()
{
        return $this->comments->....conditions....->avg('comment');
}

Then i will need to do some calculation based on the avg_like_count and avg_comment_count.

I know that this could be done using join to join all the related tables and then using whereRaw to do the calculation and filter the result in between.

Is there a better approach to deal with this kind of situation?

0 likes
5 replies
jlrdw's avatar

Depending on exactly what your needs are, use a query scope or some getters and setters (accessor / mutator).

Crazylife's avatar

But i unable to filter the append attribute with scope right... Because i want to use the paginate method from eloquent, then has to filter before call ->paginate().

jlrdw's avatar

Filter goes with pagination in the query string. Append parameters.

Crazylife's avatar

My append here not referring to the query string, it's a field like column in database where i am using getters. But it's not in the database so i can't do it in ->where('avg_like_count', '>' , 1000).

Please or to participate in this conversation.