浅谈Laravel之探秘SoftDeletes

原文发表于个人博客

Introduction

What would happen if delete() is called on a model using SoftDeletes in Laravel framework. This is the question I am asked on stackoverflow, How to create the conditions on the model of eloquent? (Laravel 5.3). So I write down this article.

SoftDeletes Trait

In laravel, we define our own model by extending Illuminate\Database\Eloquent\Model. To delete a model instance softly, we should use Illuminate\Database\Eloquent\SoftDeletes trait in our model. runSoftDelete() is the key function in SoftDeletes trait building a sql query, getting the column which is used to mark whether the record has been deleted or not and then update the column with current timestamps.

    protected function runSoftDelete()
    {
        $query = $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey());

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

        $query->update([$this->getDeletedAtColumn() => $this->fromDateTime($time)]);
    }

Procedure of Delete()

What happens when we call delete() function on a model?

Since our own model extends the Illuminate\Database\Eloquent\Model, we take a glance at it. Here is the delete() function:

public function delete()
    {
        if (is_null($this->getKeyName())) {
            throw new Exception('No primary key defined on model.');
        }

        if ($this->exists) {
            if ($this->fireModelEvent('deleting') === false) {
                return false;
            }

            // Here, we'll touch the owning models, verifying these timestamps get updated
            // for the models. This will allow any caching to get broken on the parents
            // by the timestamp. Then we will go ahead and delete the model instance.
            $this->touchOwners();

            $this->performDeleteOnModel();

            $this->exists = false;

            // Once the model has been deleted, we will fire off the deleted event so that
            // the developers may hook into post-delete operations. We will then return
            // a boolean true as the delete is presumably successful on the database.
            $this->fireModelEvent('deleted', false);

            return true;
        }
    }

The code is clear. It ensures the model has a primaryKey and the instance exists in database firstly. Then call performDeleteOnModel() function to perform deletion opreation. Attention should be paid!

Here we should know:

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.

So the exact function executes when performDeleteOnModel() called is the one with the same name in SoftDeletes trait but not the one in Model class. And now we turn back to the trait:

    protected function performDeleteOnModel()
    {
        if ($this->forceDeleting) {
            return $this->newQueryWithoutScopes()->where($this->getKeyName(), $this->getKey())->forceDelete();
        }

        return $this->runSoftDelete();
    }

Well, it calls runSoftDelete() we have talked about in the beginning. And this is procedure of soft detetion.

Problems on Getting

The asker wants to use different DELETED_AT columns when deleting. It leaves much to be desired to keep soft deletion mechanism working well by overridding getDeletedAtColumn() only. Why the deleted models are still in results even if they have been deleted softly?

When Model class is constructed, it will boot traits by calling their their boot[TraitName] method. Thus here is bootSoftDelete() method.

   protected static function bootTraits()
    {
        foreach (class_uses_recursive(get_called_class()) as $trait) {
            if (method_exists(get_called_class(), $method = 'boot'.class_basename($trait))) {
                forward_static_call([get_called_class(), $method]);
            }
        }
    }

Now let's pour attention on the SoftDeletes trait again.


    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new SoftDeletingScope);
    }

Here the trait registers a SoftDeletingScope class having an apply() method by calling static::addGlobalScope(). The method, which located in Model class stores it into $globalScopes array.

    public static function addGlobalScope(ScopeInterface $scope)
    {
        static::$globalScopes[get_called_class()][get_class($scope)] = $scope;
    }

When a query is built on a model, applyGlobalScopes() method will be called automatically, visiting instances in $globalScopes array one by one and call their apply() method.

    public function applyGlobalScopes($builder)
    {
        foreach ($this->getGlobalScopes() as $scope) {
            $scope->apply($builder, $this);
        }

        return $builder;
    }

We will lift the veil of problem now. In SoftDeletingScope class:

    public function apply(Builder $builder, Model $model)
    {
        $builder->whereNull($model->getQualifiedDeletedAtColumn());

        $this->extend($builder);
    }

It will add a constraint on every query to select those records whose DELETED_AT column is null. And this is the secret of SoftDeletes.

Dynamic DELETED_AT Column

Firstly, I need to reaffirm that I don't recommend such behaviour of using dynamic DELETED_AT column.

In order to solve the asker's problems of dynamic DELETED_AT column, you need to implement your own SoftDeletingScope class with such apply() function:

    public function apply(Builder $builder, Model $model)
    {
        $builder->where(function ($query){
            $query->where('DELETED_AT_COLUMN_1',null)->orWhere('DELETED_AT_COLUMN_2',null);
        });

        $this->extend($builder);
    }

And then overide bootSoftDeletes() with it

    public static function bootSoftDeletes()
    {
        static::addGlobalScope(new YourOwnSoftDeletingScope);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,916评论 0 23
  • 前几天梁岗老师在谈到手机问题的时候,讲到了他接触的一个学生案例:因为缺乏安全感,所以带手机入校,但最终经过...
    郝说郝道阅读 322评论 0 2
  • 本文参加#我的军训我来说#活动,本人承诺,文章内容为原创,且未在其他平台发表过。 入学前对军训的向往,军训时...
    李玉宽阅读 370评论 1 1
  • 雨慢慢停了,萧瑟地秋风吹过,吹散了满地金黄地枫叶,点点成泪,飘去远方,化作-片云。心丢掉,随萧然秋风去追却无处可寻...
    雨中的风筝阅读 317评论 0 0