2019年5月20日月曜日

laravel soft delete

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Flight extends Model
{
    use SoftDeletes;
}


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

when you call the delete method on the model, the deleted_at column will be set to the current date and time. And, when querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, use the trashed method:

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

you may force soft deleted models to appear in a result set using the  withTrashed method on the query:

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

onlyTrashed method will retrieve only soft deleted models:
$flights = App\Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

Sometimes you may wish to "un-delete" a soft deleted model. To restore a soft deleted model into an active state, use the restore method on a model instance:

$flight->restore();
You may also use the restore method in a query to quickly restore multiple models. Again, like other "mass" operations, this will not fire any model events for the models that are restored:

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

Sometimes you may need to truly remove a model from your database. To permanently remove a soft deleted model from the database, use the forceDelete method:

// Force deleting a single model instance...
$flight->forceDelete();

0 件のコメント:

コメントを投稿