2021-06-26 11:23:15 -04:00
|
|
|
<?php
|
2021-05-22 09:05:28 -04:00
|
|
|
|
2021-06-26 11:23:15 -04:00
|
|
|
namespace BookStack\Entities\Queries;
|
2021-05-22 09:05:28 -04:00
|
|
|
|
2023-05-17 12:56:55 -04:00
|
|
|
use BookStack\Activity\Models\View;
|
2023-06-10 10:08:07 -04:00
|
|
|
use BookStack\Entities\Models\BookChild;
|
|
|
|
use BookStack\Entities\Models\Entity;
|
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
|
|
use Illuminate\Support\Collection;
|
2021-05-22 09:05:28 -04:00
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
|
|
|
class Popular extends EntityQuery
|
|
|
|
{
|
2022-07-13 10:23:03 -04:00
|
|
|
public function run(int $count, int $page, array $filterModels = null)
|
2021-05-22 09:05:28 -04:00
|
|
|
{
|
|
|
|
$query = $this->permissionService()
|
2022-07-16 14:54:25 -04:00
|
|
|
->restrictEntityRelationQuery(View::query(), 'views', 'viewable_id', 'viewable_type')
|
2021-05-22 09:05:28 -04:00
|
|
|
->select('*', 'viewable_id', 'viewable_type', DB::raw('SUM(views) as view_count'))
|
|
|
|
->groupBy('viewable_id', 'viewable_type')
|
|
|
|
->orderBy('view_count', 'desc');
|
|
|
|
|
|
|
|
if ($filterModels) {
|
|
|
|
$query->whereIn('viewable_type', $this->entityProvider()->getMorphClasses($filterModels));
|
|
|
|
}
|
|
|
|
|
2023-06-10 10:08:07 -04:00
|
|
|
$entities = $query->with('viewable')
|
2021-05-22 09:05:28 -04:00
|
|
|
->skip($count * ($page - 1))
|
|
|
|
->take($count)
|
|
|
|
->get()
|
|
|
|
->pluck('viewable')
|
|
|
|
->filter();
|
2023-06-10 10:08:07 -04:00
|
|
|
|
|
|
|
$this->loadBooksForChildren($entities);
|
|
|
|
|
|
|
|
return $entities;
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function loadBooksForChildren(Collection $entities)
|
|
|
|
{
|
|
|
|
$bookChildren = $entities->filter(fn(Entity $entity) => $entity instanceof BookChild);
|
|
|
|
$eloquent = (new \Illuminate\Database\Eloquent\Collection($bookChildren));
|
|
|
|
$eloquent->load(['book' => function (BelongsTo $query) {
|
|
|
|
$query->scopes('visible');
|
|
|
|
}]);
|
2021-05-22 09:05:28 -04:00
|
|
|
}
|
2021-06-26 11:23:15 -04:00
|
|
|
}
|