软删除及其相关实现
- 在模型类中要使用SoftDeletestrait并设置$date属性数组
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Student extends Model
{
use SoftDeletes;
//设置表名
public $table = 'students';
//设置主键
public $primaryKey = 'id';
protected $dates = ['delete_at'];
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterStudentsDeletedAt extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('students', function (Blueprint $table) {
$table->timestamps();
$table->softDeletes();
});
}
}
public function destroy(Student $student)
{
$student->delete();
if (!$student->trashed()) {
return redirect()->back()->with('danger', '学生信息删除失败,学生ID:'.$student->id);
}
return redirect()->route('students.index')->with('success', '学生信息删除成功,学生ID:'.$student->id);
}
$students = Student::withTrashed()->get();
dd($students->toArray());
$students = Student::onlyTrashed()->get();
dd($students->toArray());
$student = Student::find(6);
$student->restore();
Student::withTrashed()->where('id','>',1)->restore();
Student::withTrashed()->restore();
$student = Student::find(6);
$student->history()->restore();
$student = Student::find(6);
$student->forceDelete();
网友评论