Laravel软删除

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

namespace App\Models; 

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

class 模型名 extends Model { 
        use SoftDeletes;
    //...其他一些设置 
    protected $dates = ['delete_at']; 
        public $timestamps = false;
}

2.用laravel向相应的数据库添加deleted_at字段

php artisan make:migration alter_表名_deleted_at --table=表名

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

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class Alter表名DeletedAt extends Migration { 
     public function up() { 
        Schema::table('表名', function (Blueprint $table) { 
        $table->softDeletes(); 
        }); 
     } 
     ...//其它方法 
 }

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

4.软删代码
我们在控制器中编写测试代码

$post = 模型::find(6);
$post->delete();
if($post->trashed()){
    echo '软删除成功!';
    dd($post);
}else{
    echo '软删除失败!';
}

那如果想要在查询结果中包含软删除的记录呢?可以使用SoftDeletes trait上的withTrashed方法:

$m = 模型::withTrashed()->get();
dd($m);

有时候我们只想要查看被软删除的模型,这也有招,通过SoftDeletes上onlyTrashed方法即可:

$m = 模型::onlyTrashed()->get();
dd($m);

有时候我们需要恢复被软删除的模型,可以使用SoftDeletes提供的restore方法:
恢复单个模型

$m = 模型::find(6);
$m->restore();

恢复多个模型

模型::withTrashed()->where('id','>',1)->restore();

恢复所有模型

模型::withTrashed()->restore();

恢复关联查询模型

$m = 模型::find(6);
$m->history()->restore();

如果模型配置了软删除但我们确实要删除该模型对应数据库表记录,则可以使用SoftDeletes提供的forceDelete方法:

$m = 模型::find(6);
$m->forceDelete();

猜你喜欢

转载自blog.csdn.net/weixin_34072857/article/details/87233281