CreatorTrait.php 2.1 KB
<?php
/**
 * +--------------------------------------------------------------------------------------------------------------------
 * trait :对象的用户和修改用户trait
 * +--------------------------------------------------------------------------------------------------------------------
 *
 * @copyright   Copyright
 * @author      Richer
 * @package     App\Models\Traits
 * @version     2019年10月10日,18:12:16
 * @link
 */
namespace App\Models\Traits;

use App\Models\User\User;
use Illuminate\Support\Facades\Schema;

/**
 * Trait CreatorTrait.
 */
trait CreatorTrait
{

    /**
     * 在保存的时候自动创建
     *
     * @return void
     */
    public static function bootHasCreator()
    {
        $user = auth('user')->user();
        static::creating(function ($model) use ($user) {
            $table = $model->getTable();

            if (!$model->user_id && $user && Schema::hasColumn($table, 'user_id')) {
                // 如果没有用户,默认设置为当前操作的用户
                $model->user_id     = $user->id;
            }

            // 设置 shop_id
            if (!$model->created_by && $user && Schema::hasColumn($table, 'created_by')) {
                $model->created_by     = $user->id;
            }

             // 设置 shop_id
            if (!$model->created_by && $user && Schema::hasColumn($table, 'created_model')) {
                $model->created_model  = $user::OBJ_NAME;
            }

            if (!$model->user_model && $user && Schema::hasColumn($table, 'user_model')) {
                // 如果没有用户,默认设置为当前操作的用户
                $model->user_model     = 'user';
            }
        });
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');//->withTrashed();
    }

    /**
     * @param User $user
     *
     * @return bool
     */
    public function isCreatedBy($user)
    {
        if ($user instanceof User) {
            $user = $user->id;
        }
        return $this->user_id == \intval($user);
    }
}