3 namespace BookStack\Activity\Models;
5 use BookStack\App\Model;
6 use BookStack\Permissions\Models\JointPermission;
7 use Illuminate\Database\Eloquent\Relations\HasMany;
8 use Illuminate\Database\Eloquent\Relations\MorphTo;
12 * Views are stored per-item per-person within the database.
13 * They can be used to find popular items or recently viewed items
14 * at a per-person level. They do not record every view instance as an
15 * activity. Only the latest and original view times could be recognised.
17 * @property int $views
18 * @property int $user_id
20 class View extends Model
22 protected $fillable = ['user_id', 'views'];
25 * Get all owning viewable models.
27 public function viewable(): MorphTo
29 return $this->morphTo();
32 public function jointPermissions(): HasMany
34 return $this->hasMany(JointPermission::class, 'entity_id', 'viewable_id')
35 ->whereColumn('views.viewable_type', '=', 'joint_permissions.entity_type');
39 * Increment the current user's view count for the given viewable model.
41 public static function incrementFor(Viewable $viewable): int
44 if (is_null($user) || $user->isDefault()) {
48 /** @var View $view */
49 $view = $viewable->views()->firstOrNew([
50 'user_id' => $user->id,
53 $view->forceFill(['views' => $view->views + 1])->save();
59 * Clear all views from the system.
61 public static function clearAll()
63 static::query()->truncate();