laravel orm软删除

1.新建Post模型,引用SoftDeletes

<?php

namespace App\Models;

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

class Post extends Model
{
    //引用trait
    use SoftDeletes;
    protected $dates = ['delete_at'];
}

2.新建posts迁移文件,并加入软删除字段

php artisan make:migration --create=posts
 1 <?php
 2 
 3 use Illuminate\Support\Facades\Schema;
 4 use Illuminate\Database\Schema\Blueprint;
 5 use Illuminate\Database\Migrations\Migration;
 6 
 7 class CreatePostsTable extends Migration
 8 {
 9     /**
10      * Run the migrations.
11      *
12      * @return void
13      */
14     public function up()
15     {
16         Schema::create('posts', function (Blueprint $table) {
17             $table->increments('id');
18             $table->string('name')->default('');
19             $table->string('email')->default('');
20             $table->softDeletes();
21             $table->timestamps();
22         });
23     }
24             

3.执行前以命令

php artisan migrate

4.控制器测试软删除相关命令

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Post;


class DatabaseController extends Controller
{
    public function test(){
/*      $post = Post::find(1);//找到模型
        $post->delete();//deleted_at 字段将会被设置成目前的日期和时间。
        if($post->trashed()){
            echo '软删除成功';
            dd($post);
        }else{
            echo '软删除失败';
        }*/
     /*只取出软删除数据*/
       //    $post = Post::onlyTrashed()->get();
     /*恢复软删除的数据*/
        Post::withTrashed()->where('id','=',1)->restore();




    }
}

 



posted on 2017-11-02 16:11  running-fly  阅读(1281)  评论(0)    收藏  举报

导航