顧名思義,在介紹有哪些刪除 Model 的方法可以使用。

 

 

 

基本刪除

我們在呼叫 delete 方法之前,先從資料庫取回了模型。

$flight = App\Flight::find(1);

$flight->delete();

透過鍵來刪除

如果你知道模型中的主鍵,你可以不取回模型就直接刪除它。呼叫 destroy 方法:

App\Flight::destroy(1);

App\Flight::destroy([1, 2, 3]);

App\Flight::destroy(1, 2, 3);

透過查詢來刪除

當然,你也可以在一組模型上執行刪除查詢。在這個範例中,我們將會刪除所有被標記為不活躍的航班:

$deletedRows = App\Flight::where('active', 0)->delete();

Soft Deleting(軟刪除)

意思就是在資料表多一個 deleted_at 欄位來記錄你刪除的時間,當 deleted_at 不是空值,會自動從所有的查詢結果中排除。

要在 Model 啟動軟刪除,必須在 Model 上使用 Illuminate\Database\Eloquent\SoftDeletes trait 並新增 deleted_at 欄位到你的 $dates 屬性:

use Illuminate\Database\Eloquent\SoftDeletes;

在 Model class 裡加上下面兩行程式碼。

use SoftDeletes;
protected $dates = ['deleted_at'];

應該添加 deleted_at 欄位到你的資料表。Laravel 結構產生器包含了一個輔助的方法用來建立這個欄位:( 應該是在 Migrate 地方加 )

Schema::table('flights', function ($table) {
    $table->softDeletes();
});

現在,當你在模型上呼叫 delete 方法,deleted_at 欄位將會被設定成目前的日期和時間。

要確認給定的模型實例是否已經被軟刪除,可以使用 trashed 方法:

if ($flight->trashed()) {
    //
}

查詢被 Soft Deleting 的 Model

可以藉由在查詢上呼叫 withTrashed 方法, 強迫被軟刪除的模型出現在查詢結果:

$flights = App\Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

withTrashed 方法也可以被用在關聯查詢:

$flight->history()->withTrashed()->get();

onlyTrashed 方法會只取得被軟刪除的模型:

$flights = App\Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

恢復被 Soft Deleting 的 Model

要恢復一個被軟刪除的模型回到有效狀態,必須在模型實例上使用 restore 方法:

$flight->restore();

你也可以在查詢上使用 restore 方法來快速地恢復多個模型:

App\Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();

 withTrashed 方法類似,restore 方法也可以被用在關聯:

$flight->history()->restore();

永久刪除 Model

// 強制刪除單一模型實例...
$flight->forceDelete();

// 強制刪除所有相關模型...
$flight->history()->forceDelete();

 

 


引用文章:

https://laravel.com/docs/5.3/eloquent#deleting-models

https://laravel.tw/docs/5.2/eloquent#deleting-models

arrow
arrow

    Mayuge 發表在 痞客邦 留言(0) 人氣()