shetabit/visitor

How to sort visited model by most visits?

mmdm95 opened this issue · 2 comments

mmdm95 commented

Hi, this is NOT an issue, just a question.

How can I sort my model according to number of visits?

Thanks in advanced.

easy way: can run a query by grouping by number of visits and then sort the result.

mmdm95 commented

Hi again, thanks for your reply.
I actually needs to sort something like blog by most viewed items and came up with below solution:

$visitableTable = config('visitor.table_name');

$query->select(['blogs.*'])
    ->selectRaw('COUNT(DISTINCT(' . $visitableTable . '.ip)) AS unique_visit_count')
    ->leftJoin(
        $visitableTable,
        function ($join) use ($visitableTable) {
            $join->on('blogs.id', $visitableTable . '.visitable_id')
                ->where('visitable_type', Blog::class);
        }
    )
    ->orderBy('unique_visit_count', 'desc')
    ->groupBy('blogs.id')
    ->get(); // or paginate or other things

I didn't test it yet but hope it works.

I hope that I didn't misunderstand library and its database

can mostViewed functionality be part of the library?