Depending on exactly what your needs are, use a query scope or some getters and setters (accessor / mutator).
Jul 6, 2021
5
Level 4
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?
Please or to participate in this conversation.