迁移:
public function up() { Schema::create('rewards', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->comment('操作用户'); $table->integer('target_user')->unsigned()->comment('目标用户'); $table->bigInteger('amount')->unsigned()->comment('打赏金额'); $table->morphs('rewardable'); $table->timestamps(); }); }
表结构:
模型:
<?php declare(strict_types=1); namespace ZhiyiPlusModels; use IlluminateDatabaseEloquentModel; class Reward extends Model { /** * The guarded attributes on the model. * * @var array */ protected $guarded = ['id', 'created_at', 'updated_at']; /** * Has rewardable. * * @return IlluminateDatabaseEloquentRelationsMorphTo * @author Seven Du <shiweidu@outlook.com> */ public function rewardable() { return $this->morphTo(); } /** * Has user for the rewardable. * * @author bs<414606094@qq.com> * @return IlluminateDatabaseEloquentRelationsHasOne|null */ public function user() { return $this->hasOne(User::class, 'id', 'user_id'); } /** * Has target for the rewardable. * * @return IlluminateDatabaseEloquentRelationsHasOne */ public function target() { return $this->hasOne(User::class, 'id', 'target_user'); } }
动态打赏:
资讯打赏:
用户打赏记录:
<?php declare(strict_types=1); namespace ZhiyiPlusModelsRelations; use ZhiyiPlusModelsUser; use ZhiyiPlusModelsReward; trait UserHasReward { /** * 用户的被打赏记录. * * @author bs<414606094@qq.com> * @return IlluminateDatabaseEloquentRelationsmorphMany */ public function beRewardeds() { return $this->morphMany(Reward::class, 'rewardable'); } /** * 打赏用户. * * @author bs<414606094@qq.com> * @param mix $user * @param float $amount * @return mix */ public function reward($user, $amount) { if ($user instanceof User) { $user = $user->id; } return $this->getConnection()->transaction(function () use ($user, $amount) { return $this->beRewardeds()->create([ 'user_id' => $user, 'target_user' => $this->id, 'amount' => $amount, ]); }); }
帖子打赏: