1、首先在模型中要使用SoftDeletestrait,该trait为软删除提供一系列相关方法,具体可参考源码
Illuminate\Database\Eloquent\SoftDeletes
,此外还要设置$date属性数组,将deleted_at置于其中:
<?php
namespace App\Model\Backend;
use App\Http\Response;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Request;
class User extends Model
{
use SoftDeletes;
protected $table = 'users'; //表名
protected $primaryKey = 'id'; //主键
protected $datas = ['deleted_at'];
2、向数据库中的相应数据表添加
delete_at
字段
#生成一个迁移文件
php artisan make:migration add_deleted_at_to_users_table --table=users
#执行迁移文件
php artisan migrate
<?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();
});
}
#模型里面执行delete方法就行了
self::whereIn('id', $ids)->delete(); //删除用户
withTrashed() 显示所有数据
onlyTrashed() 显示删除数所
restore()还原数据