萌新第一次用Laravel的ORM,关于软删除问题?

故人重来

问题描述

我这边使用的Laravel的ORM。经常用的软删除字段。但是Laravel的软删除字段默认值null。我不知道这个走了索引没?所以有没有大佬改造过laravel的ORM继承软删除类的。把他查询默认查询为0,以及字段类型为int

220 1 1
1个回答

故人重来

还是记录下吧。
修改方案。

在模型文件增加一个方法。要重写 SoftDeletingScope 这个
    /**
     * 模型日期的存储格式
     *
     * @var string
     */
    protected $dateFormat = 'U';

    use SoftDeletes;

    public static function bootSoftDeletes(): void
    {
        static::addGlobalScope(new SoftDeletingScope());
    }
<?php

namespace app\common\model;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope as SystemSoftDeletingScope;

class SoftDeletingScope extends SystemSoftDeletingScope
{
    /**
     * 未删除的默认值.
     */
    const NOT_DELETE_DEFAULT_VALUE = 0;

    /**
     * Apply the scope to a given Eloquent query builder.
     * Filter soft deleted data by default
     *
     * @param Builder                             $builder
     * @param Model $model
     *
     * @return void
     */
    public function apply(Builder $builder, Model $model): void
    {
        $builder->where($model->getQualifiedDeletedAtColumn(), self::NOT_DELETE_DEFAULT_VALUE);
    }

    /* Add the restore extension to the builder.
    * Add restore extensions to restore soft deleted data back to normal data
    *
    * @param IlluminateDatabaseEloquentBuilder $builder
    *
    * @return void
    */
    protected function addRestore(Builder $builder)
    {
        $builder->macro('restore', function (Builder $builder) {
            $builder->withTrashed();

            return $builder->update([$builder->getModel()->getDeletedAtColumn() => self::NOT_DELETE_DEFAULT_VALUE]);
        });
    }

    /**
     * Add the without-trashed extension to the builder.
     * Filtering data that has been soft deleted
     *
     * @param Builder $builder
     *
     * @return void
     */
    protected function addWithoutTrashed(Builder $builder): void
    {
        $builder->macro('withoutTrashed', function (Builder $builder) {
            $model = $builder->getModel();

            $builder->withoutGlobalScope($this)->where($model->getQualifiedDeletedAtColumn(),
                self::NOT_DELETE_DEFAULT_VALUE);

            return $builder;
        });
    }

    /**
     * Add the only-trashed extension to the builder.
     * Add an extension to retrieve only data that has been soft deleted
     *
     * @param Builder $builder
     *
     * @return void
     */
    protected function addOnlyTrashed(Builder $builder): void
    {
        $builder->macro('onlyTrashed', function (Builder $builder) {
            $model = $builder->getModel();

            $builder->withoutGlobalScope($this)->where($model->getQualifiedDeletedAtColumn(), '!=',
                self::NOT_DELETE_DEFAULT_VALUE);

            return $builder;
        });
    }
}
  • 暂无评论
×
🔝