laravel 多态映射(打赏为例)

Posted sgm4231

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel 多态映射(打赏为例)相关的知识,希望对你有一定的参考价值。

迁移:

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 <[email protected]>
     */
    public function rewardable()
    {
        return $this->morphTo();
    }
    /**
     * Has user for the rewardable.
     *
     * @author bs<[email protected]>
     * @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<[email protected]>
     * @return \\Illuminate\\Database\\Eloquent\\Relations\\morphMany
     */
    public function beRewardeds()
    {
        return $this->morphMany(Reward::class, ‘rewardable‘);
    }

    /**
     * 打赏用户.
     *
     * @author bs<[email protected]>
     * @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 多态映射(打赏为例)的主要内容,如果未能解决你的问题,请参考以下文章

laravel下的ORM数据映射之自由畅想

laravel特殊功能代码片段集合

laravel5.5学习2-路由系统

需要一种有效的方法来避免使用 Laravel 5 重复代码片段

Laravel:如何在控制器的几种方法中重用代码片段

面向对象-通过代码分析多态