代码之家  ›  专栏  ›  技术社区  ›  M. Ko

Laravel自定义软删除还原无法正常工作

  •  0
  • M. Ko  · 技术社区  · 5 年前

    deleted_flag Larave软删除功能的微小整数。

    trait  CustomSoftDeleteTrait
    {
        use SoftDeletes;
    
        protected function runSoftDelete()
        {
            $query = $this->setKeysForSaveQuery($this->newModelQuery());
    
            $time = $this->freshTimestamp();
    
            $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];
    
            $this->{$this->getDeletedAtColumn()} = $time;
    
            if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
                $this->{$this->getUpdatedAtColumn()} = $time;
    
                $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
            }
    
            $columns[$this->getDeletedFlagColumn()] = 1; //<-- here is the deleting
    
            $query->update($columns);
        }
    
        protected function restore()
        {            
            if ($this->fireModelEvent('restoring') === false) {
                return false;
            }
    
            $this->{$this->getDeletedFlagColumn()} = 0; //<-- here is restoring
            $this->{$this->getDeletedAtColumn()} = null;    
    
            $this->exists = true;
    
            $result = $this->save();
    
            $this->fireModelEvent('restored', false);
    
            return $result;
        }
    
        public function getDeletedFlagColumn()
        {
            return defined('static::DELETED_FLAG') ? static::DELETED_FLAG : 'deleted_flag';
        }
    }
    

    模型的移植,

    Schema::create('families', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->integer('family_type');
    
                $table->timestamp('create_date')->nullable();
                $table->timestamp('update_date')->nullable();
                $table->timestamp('delete_date')->nullable();
                $table->tinyInteger('delete_flg')->nullable();
            });
    

    使用模型中的自定义特征,

    class Family extends Model
    {
        use CustomSoftDeleteTrait;
    
        protected $guarded = [
            'id',
        ];
    
        const CREATED_AT = 'create_date';
        const UPDATED_AT = 'update_date';
        const DELETED_AT = 'delete_date';
        const DELETED_FLAG = 'delete_flg';
    }
    

    $family->delete() delete_date delete_flg 已设置。恢复模型时,只有一个字段 删除\u日期 删除\u flg 字段保持不变为1。

    0 回复  |  直到 5 年前
        1
  •  0
  •   shock_gone_wild    5 年前

    这是一个相当棘手的错误。

    但是您所要做的就是在自定义Trait中将restore()函数的修饰符从protected改为public。

      protected function restore() { /**/ }
    

    应该变成

      public function restore() { /**/ }