Laravel5.1 框架模型软删除操作实例分析

吾爱主题 阅读:145 2021-09-26 13:47:00 评论:0

本文实例讲述了Laravel5.1 框架模型软删除操作。分享给大家供大家参考,具体如下:

软删除是比较实用的一种删除手段,比如说 你有一本账 有一笔记录你觉得不对给删了 过了几天发现不应该删除,这时候软删除的目的就实现了 你可以找到已经被删除的数据进行操作 可以是还原也可以是真正的删除。

1 普通删除

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

1.1 直接通过主键删除

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

1.2 获取model后删除

?
1 2 3 4 5 public function getDelete() {    $article = Article::find(3);    $article -> delete (); }

1.3 批量删除

?
1 2 3 4 5 6 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列 如果没有就添加这个列。

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

?
1 2 3 4 5 6 7 8 9 10 11 12 13 <?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列到数据表:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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 实现软删除

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

?
1 2 3 4 5 public function getDelete() {    $article = Article::first();    $article -> delete (); }

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

2.3 判断数据是否被软删除

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

2.4 查询到被软删除的数据

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

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

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

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

2.5 恢复被软删除的数据

?
1 2 3 4 5 public function getIndex() {    $article = Article::withTrashed()->find(6);    $article ->restore(); }

2.6 永久删除数据

?
1 2 3 4 5 public function getIndex() {    $article = Article::withTrashed()->find(6);    $article ->forceDelete(); }

希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/sun-kang/p/7512737.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容