淺談Laravel之探秘SoftDeletes

原文發(fā)表于個(gè)人博客

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);
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末康愤,一起剝皮案震驚了整個(gè)濱河市冶匹,隨后出現(xiàn)的幾起案子迫横,更是在濱河造成了極大的恐慌橘券,老刑警劉巖泞莉,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件惫搏,死亡現(xiàn)場離奇詭異笋鄙,居然都是意外死亡岭佳,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門世蔗,熙熙樓的掌柜王于貴愁眉苦臉地迎上來端逼,“玉大人,你說我怎么就攤上這事污淋《ヌ玻” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵寸爆,是天一觀的道長礁鲁。 經(jīng)常有香客問我,道長赁豆,這世上最難降的妖魔是什么仅醇? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮魔种,結(jié)果婚禮上析二,老公的妹妹穿的比我還像新娘。我一直安慰自己节预,他們只是感情好叶摄,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著安拟,像睡著了一般蛤吓。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上去扣,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天柱衔,我揣著相機(jī)與錄音,去河邊找鬼愉棱。 笑死唆铐,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的奔滑。 我是一名探鬼主播艾岂,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼朋其!你這毒婦竟也來了王浴?” 一聲冷哼從身側(cè)響起脆炎,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎氓辣,沒想到半個(gè)月后秒裕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钞啸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年几蜻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片体斩。...
    茶點(diǎn)故事閱讀 39,785評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡梭稚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出絮吵,到底是詐尸還是另有隱情弧烤,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布蹬敲,位于F島的核電站暇昂,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏粱栖。R本人自食惡果不足惜话浇,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一脏毯、第九天 我趴在偏房一處隱蔽的房頂上張望闹究。 院中可真熱鬧,春花似錦食店、人聲如沸渣淤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽价认。三九已至,卻和暖如春自娩,著一層夾襖步出監(jiān)牢的瞬間用踩,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工忙迁, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留脐彩,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓姊扔,卻偏偏與公主長得像惠奸,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子恰梢,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,491評論 0 23
  • 前幾天梁崗老師在談到手機(jī)問題的時(shí)候佛南,講到了他接觸的一個(gè)學(xué)生案例:因?yàn)槿狈Π踩泄j詭謾C(jī)入校,但最終經(jīng)過...
    郝說郝道閱讀 316評論 0 2
  • 本文參加#我的軍訓(xùn)我來說#活動(dòng)嗅回,本人承諾及穗,文章內(nèi)容為原創(chuàng),且未在其他平臺發(fā)表過绵载。 入學(xué)前對軍訓(xùn)的向往拥坛,軍訓(xùn)時(shí)...
    李玉寬閱讀 359評論 1 1
  • 雨慢慢停了,蕭瑟地秋風(fēng)吹過尘分,吹散了滿地金黃地楓葉猜惋,點(diǎn)點(diǎn)成淚,飄去遠(yuǎn)方培愁,化作-片云著摔。心丟掉,隨蕭然秋風(fēng)去追卻無處可尋...
    雨中的風(fēng)箏閱讀 307評論 0 0