3 namespace BookStack\Actions;
5 use BookStack\Auth\Permissions\JointPermission;
6 use BookStack\Interfaces\Viewable;
8 use Illuminate\Database\Eloquent\Relations\HasMany;
9 use Illuminate\Database\Eloquent\Relations\MorphTo;
13 * Views are stored per-item per-person within the database.
14 * They can be used to find popular items or recently viewed items
15 * at a per-person level. They do not record every view instance as an
16 * activity. Only the latest and original view times could be recognised.
18 * @property int $views
19 * @property int $user_id
21 class View extends Model
23 protected $fillable = ['user_id', 'views'];
26 * Get all owning viewable models.
28 public function viewable(): MorphTo
30 return $this->morphTo();
33 public function jointPermissions(): HasMany
35 return $this->hasMany(JointPermission::class, 'entity_id', 'viewable_id')
36 ->whereColumn('views.viewable_type', '=', 'joint_permissions.entity_type');
40 * Increment the current user's view count for the given viewable model.
42 public static function incrementFor(Viewable $viewable): int
45 if (is_null($user) || $user->isDefault()) {
49 /** @var View $view */
50 $view = $viewable->views()->firstOrNew([
51 'user_id' => $user->id,
54 $view->forceFill(['views' => $view->views + 1])->save();
60 * Clear all views from the system.
62 public static function clearAll()
64 static::query()->truncate();