93 lines
2.5 KiB
PHP
93 lines
2.5 KiB
PHP
<?php
|
||
|
||
namespace kernel\app_modules\view\models;
|
||
|
||
use Illuminate\Database\Eloquent\Model;
|
||
use kernel\app_modules\view\interfaces\Viewable;
|
||
use kernel\modules\user\models\User;
|
||
|
||
// Добавить @property
|
||
/**
|
||
* @property int $id
|
||
* @property int $status
|
||
*/
|
||
class View extends Model
|
||
{
|
||
const DISABLE_STATUS = 0;
|
||
const ACTIVE_STATUS = 1;
|
||
|
||
protected $table = 'view';
|
||
|
||
protected $fillable = [
|
||
'user_id',
|
||
'ip_address',
|
||
'user_agent',
|
||
];
|
||
|
||
/**
|
||
* Получить родительскую модель (пост, комментарий, файл и т.д.)
|
||
*/
|
||
public function viewable(): \Illuminate\Database\Eloquent\Relations\MorphTo
|
||
{
|
||
return $this->morphTo();
|
||
}
|
||
|
||
/**
|
||
* Пользователь, который просмотрел
|
||
*/
|
||
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
||
{
|
||
return $this->belongsTo(User::class);
|
||
}
|
||
|
||
/**
|
||
* Увеличить счетчик просмотров для модели
|
||
*/
|
||
public static function track(Viewable $viewable)
|
||
{
|
||
// Проверяем, не просматривал ли уже пользователь этот элемент
|
||
//$existingView = static::forViewable($viewable)->first();
|
||
|
||
// if (!$existingView) {
|
||
// return static::create([
|
||
// 'user_id' => null,
|
||
// 'viewable_id' => $viewable->id,
|
||
// 'viewable_type' => get_class($viewable),
|
||
// ]);
|
||
// }
|
||
|
||
return static::create([
|
||
'user_id' => null,
|
||
'viewable_id' => $viewable->id,
|
||
'viewable_type' => get_class($viewable),
|
||
]);
|
||
|
||
//return $existingView;
|
||
}
|
||
|
||
/**
|
||
* Scope для поиска просмотров определенной модели
|
||
*/
|
||
public function scopeForViewable($query, Viewable $viewable)
|
||
{
|
||
return $query->where('viewable_id', $viewable->id)
|
||
->where('viewable_type', get_class($viewable))
|
||
->when(auth()->check(), function ($q) {
|
||
$q->where('user_id', auth()->id());
|
||
}, function ($q) {
|
||
$q->where('ip_address', request()->ip());
|
||
});
|
||
}
|
||
|
||
/**
|
||
* @return string[]
|
||
*/
|
||
public static function getStatus(): array
|
||
{
|
||
return [
|
||
self::DISABLE_STATUS => "Не активный",
|
||
self::ACTIVE_STATUS => "Активный",
|
||
];
|
||
}
|
||
|
||
} |