Laravel设置软删除及其恢复系列操作

软删除及其相关实现

  • 在模型类中要使用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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容