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

2017-11-23  本文已影响0人  老王谈编程

软删除及其相关实现

<?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();
上一篇下一篇

猜你喜欢

热点阅读