77 lines
1.5 KiB
PHP
77 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Models\Presenters\CommentPresenter;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
|
|
use Maize\Markable\Markable;
|
|
use Maize\Markable\Models\Like;
|
|
|
|
class Comment extends Model
|
|
{
|
|
use HasFactory, SoftDeletes, Markable;
|
|
|
|
protected static $marks = [
|
|
Like::class
|
|
];
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var string[]
|
|
*/
|
|
protected $fillable = [
|
|
'body'
|
|
];
|
|
|
|
public function presenter()
|
|
{
|
|
return new CommentPresenter($this);
|
|
}
|
|
|
|
public function user()
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
|
|
public function scopeParent(Builder $builder)
|
|
{
|
|
$builder->whereNull('parent_id');
|
|
}
|
|
|
|
public function children()
|
|
{
|
|
return $this->hasMany(Comment::class, 'parent_id')->oldest();
|
|
}
|
|
|
|
public function commentable()
|
|
{
|
|
return $this->morphTo();
|
|
}
|
|
|
|
public function parent()
|
|
{
|
|
return $this->hasOne(Comment::class, 'id', 'parent_id');
|
|
}
|
|
|
|
// Recursevly calculates how deep the nesting is
|
|
public function depth(): int
|
|
{
|
|
return $this->parent
|
|
? $this->parent->depth() + 1
|
|
: 0;
|
|
}
|
|
|
|
/**
|
|
* Get cached like count
|
|
*/
|
|
public function likeCount(): int
|
|
{
|
|
return cache()->remember('commentLikes' . $this->id, 300, fn() => $this->likes->count());
|
|
}
|
|
}
|