5

如何預設為每個模型及遷移加上軟刪除?

 1 year ago
source link: https://calvertyang.github.io/2022/10/26/how-to-add-soft-deletes-to-every-model-migration-by-default/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何預設為每個模型及遷移加上軟刪除?

2022-10-26

約 1692 字 / 需 9 分鐘閱讀

原文:Povilas KoropHow to Add Soft Deletes to Every Model/Migration By Default?

有太多次我的客戶要求我恢復已刪除的資料。以防萬一,我非常喜歡對幾乎所有的 Eloquent 模型使用軟刪除功能。那麼,如何使該過程自動化一點呢?

一般來說,我們如何加入軟刪除呢?透過將 Trait 加入到模型中:

use Illuminate\Database\Eloquent\SoftDeletes;
 
class Task extends Model
{
    use SoftDeletes;
}

此外,我們需要將 deleted_at 加到遷移中:

Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    // ... other fields
    $table->timestamps();
    $table->softDeletes(); // THIS ONE
});

現在,我們要如何確保每當我們執行 php artisan make:modelphp artisan make:migration 時,新檔案都會包含這些修改?

我們可以自訂預設的樣板(Stub)檔案,新檔案會基於它們來建立。

執行這個指令:

php artisan stub:publish

它會將檔案從 /vendor 資料夾複製到名為 /stubs 的資料夾中。在這些檔案中,讓我們先關注在模型及遷移上。



stubs/migration.create.stub

// ... other code public function up() { Schema::create('{{ table }}', function (Blueprint $table) { $table->id(); $table->timestamps(); }); }

所以,我們要做的就是在這加上第三行:

public function up()
{
    Schema::create('{{ table }}', function (Blueprint $table) {
        $table->id();
        $table->timestamps();
        $table->softDeletes();
    });
}

同樣地,也要修改模型的樣板檔。



stubs/model.stub

namespace {{ namespace }}; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class {{ class }} extends Model { use HasFactory; }

加上 SoftDeletes 後:

namespace {{ namespace }};
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
 
class {{ class }} extends Model
{
    use HasFactory, SoftDeletes;
}

就是這樣!現在試著執行 php artisan make:model SomeModel -m 就能看到軟刪除自動被加入到模型及遷移中了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK