Level 20
I believe you need to use the group by categories.
$post = Post::with('categories')->findOrFail(1);
$categoryIds = $post->categories->pluck('id');
$relatedPosts = Post::query()
->where('posts.id', '<>', $post->id)
->whereHas('categories', function ($q) use ($categoryIds) {
$q->whereIn('categories.id', $categoryIds);
})
->withCount([
'categories as matched_categories_count' => function ($q) use ($categoryIds) {
$q->whereIn('categories.id', $categoryIds);
}
])
->orderByDesc('matched_categories_count')
->get();
1 like