54 lines
1.3 KiB
PHP
54 lines
1.3 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Traits;
|
||
|
|
|
||
|
|
use App\Models\Liker;
|
||
|
|
use App\Contracts\Likerable;
|
||
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
||
|
|
|
||
|
|
trait Canlike
|
||
|
|
{
|
||
|
|
//通用点赞功能
|
||
|
|
public function like(Likerable $likerable):liker
|
||
|
|
{
|
||
|
|
$Likers = new Liker([
|
||
|
|
'likedable_id' => $this->primaryId(),
|
||
|
|
'likedable_type' => get_class(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
$likerable->Likers()->save($Likers);
|
||
|
|
return $Likers;
|
||
|
|
}
|
||
|
|
|
||
|
|
// 取消点赞
|
||
|
|
|
||
|
|
public function dislike(Likerable $likerable)
|
||
|
|
{
|
||
|
|
$result = Liker::where('likedable_id',$this->primaryId())
|
||
|
|
->where('likedable_type',get_class())
|
||
|
|
->where('like_id',$likerable->primaryId())
|
||
|
|
->where('like_type', get_class($likerable))
|
||
|
|
->delete();
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
//点赞列表
|
||
|
|
public function likers(): MorphMany
|
||
|
|
{
|
||
|
|
return $this->morphMany(Liker::class,'likedable');
|
||
|
|
}
|
||
|
|
|
||
|
|
// 是否点赞
|
||
|
|
public function hasLiked(Likerable $likerable)
|
||
|
|
{
|
||
|
|
$result = Liker::where('likedable_id',$this->primaryId())
|
||
|
|
->where('likedable_type',get_class())
|
||
|
|
->where('like_id',$likerable->primaryId())
|
||
|
|
->where('like_type', get_class($likerable))
|
||
|
|
->exists();
|
||
|
|
return $result;
|
||
|
|
}
|
||
|
|
|
||
|
|
|
||
|
|
}
|