繁体   English   中英

Laravel:正确覆盖SoftDeletes特性

[英]Laravel: Override SoftDeletes trait properly

我想打一个使用特征SoftDeletes名为SoftDeletesWithStatus也将更新状态栏。 我的问题是我想在SoftDeletes的函数中间实现代码,如下所示:

protected function runSoftDelete() {
    $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
    $time = $this->freshTimestamp();
    $columns = [$this->getDeletedAtColumn() => $this->fromDateTime($time)];

   //I want to implement my code here

    $this->{$this->getDeletedAtColumn()} = $time;
    if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
        $this->{$this->getUpdatedAtColumn()} = $time;
        $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
    }
    $query->update($columns);
}

public function restore() {
    if ($this->fireModelEvent('restoring') === false) {
        return false;
    }
    $this->{$this->getDeletedAtColumn()} = null;

    //I want to implement my code here

    $this->exists = true;
    $result = $this->save();
    $this->fireModelEvent('restored', false);
    return $result;
}

将代码复制粘贴到SoftDeletesWithStatus特征中并在其中实现我的代码是否是更好的解决方案?

谢谢您的帮助。

我最接近该解决方案的是:

<?php
namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

//Status 1 = Activated; Status 99 = Deleted
trait SoftDeletesWithStatus {
    use SoftDeletes {
        SoftDeletes::runSoftDelete as parentRunSoftDelete;
        SoftDeletes::restore as parentRestore;
    }

    public function getStatusColumn() {
        return defined('static::STATUS') ? static::STATUS : 'status';
    }

    public function runSoftDelete() {
        $this->parentRunSoftDelete();
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());
        $columns = [$this->getStatusColumn() => 99];
        $this->{$this->getDeletedAtColumn()} = 99;
        $query->update($columns);
    }

    public function restore() {
        $result = $this->parentRestore();
        $this->{$this->getStatusColumn()} = 1;
        $this->save();
        return $result;
    }
}

然后,我只是在想要的模型中使用我的特征:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;
use App\SoftDeletesWithStatus;

class MyModel extends Model {
    use SoftDeletesWithStatus;
}

我认为JacupoStanchis解决方案并不完整。
通过runSoftDeleterestore新特性的方法无法处理关系。

假设您有一个简单的关系,例如:
Author 1-n Book

工作示例:

$Author->delete();
$Author->restore();

不起作用的示例:

$Book->author()->delete();
$Book->author()->restore();

多亏了Xdebug,我才能为“无法正常工作的示例”找到解决方案。
顺便说一句。 在我的情况下,需要一个字符串列,因此我可以结合使用已删除状态和唯一约束。 因此方法不同。

app/Traits/SoftDeletes.php

<?php

namespace App\Traits;

use App\Overrides\Eloquent\SoftDeletingScope;

trait SoftDeletes
{
    use \Illuminate\Database\Eloquent\SoftDeletes;

    /**
    * Boot the soft deleting trait for a model.
    *
    * @return void
    */
    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new SoftDeletingScope);
    }

    /**
    * Perform the actual delete query on this model instance.
    *
    * @return void
    */
    protected function runSoftDelete()
    {
        $query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());

        $time = $this->freshTimestamp();

        $columns = [
            $this->getDeletedAtColumn() => $this->fromDateTime($time),
            $this->getDeletedHashColumn() => uniqid(),
        ];

        $this->{$this->getDeletedAtColumn()} = $time;

        if ($this->timestamps && ! is_null($this->getUpdatedAtColumn())) {
            $this->{$this->getUpdatedAtColumn()} = $time;

            $columns[$this->getUpdatedAtColumn()] = $this->fromDateTime($time);
        }

        $query->update($columns);
    }

    /**
    * Restore a soft-deleted model instance.
    *
    * @return bool|null
    */
    public function restore()
    {
        // If the restoring event does not return false, we will proceed with this
        // restore operation. Otherwise, we bail out so the developer will stop
        // the restore totally. We will clear the deleted timestamp and save.
        if ($this->fireModelEvent('restoring') === false) {
            return false;
        }

        $this->{$this->getDeletedAtColumn()} = null;
        $this->{$this->getDeletedHashColumn()} = '';

        // Once we have saved the model, we will fire the "restored" event so this
        // developer will do anything they need to after a restore operation is
        // totally finished. Then we will return the result of the save call.
        $this->exists = true;

        $result = $this->save();

        $this->fireModelEvent('restored', false);

        return $result;
    }

    /**
    * Get the name of the "deleted at" column.
    *
    * @return string
    */
    public function getDeletedHashColumn()
    {
        return defined('static::DELETED_HASH') ? static::DELETED_HASH : 'deleted_hash';
    }

}

app/Overrides/Eloquent/SoftDeletingScope.php

<?php

namespace App\Overrides\Eloquent;

use Illuminate\Database\Eloquent;

class SoftDeletingScope extends Eloquent\SoftDeletingScope
{

    /**
    * Extend the query builder with the needed functions.
    *
    * @param  \Illuminate\Database\Eloquent\Builder  $builder
    * @return void
    */
    public function extend(Eloquent\Builder $builder)
    {
        foreach ($this->extensions as $extension) {
            $this->{"add{$extension}"}($builder);
        }

        $builder->onDelete(function (Eloquent\Builder $builder) {
            $deletedAtColumn = $this->getDeletedAtColumn($builder);
            $deletedHashColumn = $builder->getModel()->getDeletedHashColumn();

            return $builder->update([
                $deletedAtColumn => $builder->getModel()->freshTimestampString(),
                $deletedHashColumn => uniqid(),
            ]);
        });
    }

    /**
    * Add the restore extension to the builder.
    *
    * @param  \Illuminate\Database\Eloquent\Builder  $builder
    * @return void
    */
    protected function addRestore(Eloquent\Builder $builder)
    {
        $builder->macro('restore', function (Eloquent\Builder $builder) {
            $builder->withTrashed();

            return $builder->update([
                $builder->getModel()->getDeletedAtColumn() => null,
                $builder->getModel()->getDeletedHashColumn() => '',
            ]);
        });
    }
}

我在新的Trait中添加了bootSoftDeletes方法,该方法将自定义SoftDeletingScope添加到了全局范围。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM