您的位置:首页 > 编程语言 > PHP开发

laravel框架总结 -- 软删除

2017-07-25 16:53 302 查看
当模型被软删除时,它们并不会真的从数据库中被移除。而是会在模型上设置一个 deleted_at 属性并将其添加到数据库。如果对应模型被软删除,则deleted_at字段的值为删除时间,否则该值为空。

 

1.做一些设置

  首先在模型类中要使用SoftDeletestrait,该trait为软删除提供一系列相关方法,具体可参考源码Illuminate\Database\Eloquent\SoftDeletes,此外还要设置$date属性数组,将deleted_at置于其中:

<?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;

    use Illuminate\Database\Eloquent\SoftDeletes;

    class Post extends Model {

        use SoftDeletes;

        //...其他一些设置

        protected $dates = ['delete_at'];

    }    

2.向数据库中的相应数据表添加delete_at字段

  1>这里我们使用数据迁移来实现

  php artisan make:migration alter_posts_deleted_at --table=posts

 

  2>此时在database/migrations文件夹下会生成一个相应文件,更改如下

<?php

    use Illuminate\Database\Schema\Blueprint;

    use Illuminate\Database\Migrations\Migration;

    class AlterPostsDeletedAt extends Migration {

        /**

        * Run the migrations.

        *

        * @return void

        */

        public function up() {

            Schema::table('posts', function (Blueprint $table) {

                $table->softDeletes();

            });

        }

        ...//其它方法

    }                

  3>再次运行命令 php artisan migrate ,发现数据库相应的数据表中已经有delete_at字段了

 

3.使用方法

  在模型上调用 delete 方法时,deleted_at 字段将会被设置成目前的日期和时间。而且,当查找有启用软删除的模型时,被软删除的模型将会自动从所有查找结果中排除。

  //在模型上调用delete方法

  $post = Post::find(6); $post->delete();

  //要确认指定的模型实例是否已经被软删除,可以使用 trashed 方法:  

   if($post->trashed()){

    echo '软删除成功!';

    dd($post);

  }else{

    echo '软删除失败!';

  }

 

  //查找被软删除的模型

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

 

  //onlyTrashed 方法会只获取已被软删除的模型:

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

 

  //恢复单个已经被软删除的模型

  $flight = Flight::withTrashed()-find(1); //这里要注意如果被软删除直接find是查不到的

  $flight->restore();

  //恢复多个模型

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

 

  // 强制删除单个模型实例...

  $flight->forceDelete();

  // 强制删除所有相关模型...

  $flight->history()->forceDelete();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: