码迷,mamicode.com
首页 > 其他好文 > 详细

laravel 多态映射(打赏为例)

时间:2019-04-30 17:06:06      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:span   oat   打赏   comm   目标   use   big   pes   tab   

迁移:

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 Zhiyi\Plus\Models;

use Illuminate\Database\Eloquent\Model;

class Reward extends Model
{
    /**
     * The guarded attributes on the model.
     *
     * @var array
     */
    protected $guarded = [‘id‘, ‘created_at‘, ‘updated_at‘];
    /**
     * Has rewardable.
     *
     * @return \Illuminate\Database\Eloquent\Relations\MorphTo
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function rewardable()
    {
        return $this->morphTo();
    }
    /**
     * Has user for the rewardable.
     *
     * @author bs<414606094@qq.com>
     * @return \Illuminate\Database\Eloquent\Relations\HasOne|null
     */
    public function user()
    {
        return $this->hasOne(User::class, ‘id‘, ‘user_id‘);
    }
    /**
     * Has target for the rewardable.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function target()
    {
        return $this->hasOne(User::class, ‘id‘, ‘target_user‘);
    }
}

动态打赏:

技术图片

资讯打赏:

技术图片

用户打赏记录:

技术图片

<?php

declare(strict_types=1);

namespace Zhiyi\Plus\Models\Relations;

use Zhiyi\Plus\Models\User;
use Zhiyi\Plus\Models\Reward;

trait UserHasReward
{
    /**
     * 用户的被打赏记录.
     *
     * @author bs<414606094@qq.com>
     * @return \Illuminate\Database\Eloquent\Relations\morphMany
     */
    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,
            ]);
        });
    }

帖子打赏:

技术图片

 

laravel 多态映射(打赏为例)

标签:span   oat   打赏   comm   目标   use   big   pes   tab   

原文地址:https://www.cnblogs.com/sgm4231/p/10796778.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!