使用Laravel5.1 框架怎么实现模型软删除操作

2023-06-06

使用Laravel5.1 框架怎么实现模型软删除操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

1 普通删除

在软删除之前咱先看看普通的删除方法:

1.1 直接通过主键删除

  public function getDelete()
  {
    Article::destroy(1);
    Article::destroy([1,2,3]);
  }

1.2 获取model后删除

  public function getDelete()
  {
    $article = Article::find(3);
    $article->delete();
  }

1.3 批量删除

  public function getDelete()
  {
    // 返回一个整形 删除了几条数据
    $deleteRows = Article::where('id','>',3)->delete();
    dd($deleteRows);  // 2
  }

2 软删除

2.1 准备工作

如果你要实现软删除 你应该提前做3件事情:

  1. 添加deleted_at 到模型的 $date 属性中。

  2. 在模型中使用 Illuminate\Database\Eloquent\SoftDeletes 这个trait

  3. 保证你的数据表中有deleted_at列 如果没有就添加这个列。

首先我们做第一步和第二步:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
  // 使用SoftDeletes这个trait
  use SoftDeletes;
  // 白名单
  protected $fillable = ['title', 'body'];
  // dates
  protected $dates = ['deleted_at'];
}

然后我们生成一个迁移文件来增加deleted_at列到数据表:

class InsertDeleteAtIntroArticles extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::table('articles', function (Blueprint $table) {
      $table->softDeletes();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::table('articles', function (Blueprint $table) {
      $table->dropSoftDeletes();
    });
  }
}

2.2 实现软删除

现在我们就可以删除一条数据试试啦:

  public function getDelete()
  {
    $article = Article::first();
    $article->delete();
  }

↑ 当我们删了这条数据后 在数据表中的表示是 deleted_at 不为空 它是一个时间值,当delete_at不为空时 证明这条数据已经被软删除了。

2.3 判断数据是否被软删除

if ($article->trashed()){
      echo '这个模型已经被软删除了';
    }

2.4 查询到被软删除的数据

有一点需要注意,当数据被软删除后 它会自动从查询数据中排除、就是它无法被一般的查询语句查询到。当我们想要查询软删除数据时 可以使用withTrashed方法

  public function getIndex()
  {
    $article = Article::withTrashed()->first();
    if ($article->trashed()){
      echo '被软删除了';  // 代码会执行到这一行
    }
  }

我们还可以使用onlyTrashed,它和withTrashed的区别是 它只获得软删除的数据。

  public function getIndex()
  {
    $articles = Article::onlyTrashed()->where('id','<','10')->get()->toArray();
    dd($articles);
  }

2.5 恢复被软删除的数据

  public function getIndex()
  {
    $article = Article::withTrashed()->find(6);
    $article->restore();
  }

2.6 永久删除数据

  public function getIndex()
  {
    $article = Article::withTrashed()->find(6);
    $article->forceDelete();
  }

关于使用Laravel5.1 框架怎么实现模型软删除操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注本站行业资讯频道了解更多相关知识。

《使用Laravel5.1 框架怎么实现模型软删除操作.doc》

下载本文的Word格式文档,以方便收藏与打印。