45 lines
1.1 KiB
PHP
45 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
use App\Contracts\Rewardable;
|
|
use App\Models\Reward;
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
|
|
trait CanReward
|
|
{
|
|
//通用打赏功能
|
|
public function reward(Rewardable $rewardable, $amount, $comment_text=null):reward
|
|
{
|
|
$reward = new Reward([
|
|
'amount' => $amount,
|
|
'comment' => $comment_text,
|
|
'rewarded_id' => $this->primaryId(),
|
|
'rewarded_type' => get_class(),
|
|
]);
|
|
|
|
$rewardable->rewards()->save($reward);
|
|
return $reward;
|
|
}
|
|
|
|
//打赏列表
|
|
public function rewards(): MorphMany
|
|
{
|
|
return $this->morphMany(Reward::class);
|
|
}
|
|
|
|
//打赏次数
|
|
public function rewardCount(Rewardable $rewardable): int
|
|
{
|
|
return $this->rewards()
|
|
->where([
|
|
'rewardable_id' => $rewardable->primaryId(),
|
|
'rewardable_type' => get_class($rewardable),
|
|
])
|
|
->count();
|
|
}
|
|
|
|
private function primaryId(): string
|
|
{
|
|
return (string)$this->getAttribute($this->primaryKey);
|
|
}
|
|
} |