浅谈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);
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,176评论 5 469
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,190评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,232评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,953评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,879评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,177评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,626评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,295评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,436评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,365评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,414评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,096评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,685评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,771评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,987评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,438评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,032评论 2 341

推荐阅读更多精彩内容

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