2017年9月27日 星期三

Laravel ,softdelete


//下指令
php artisan make:migration add_deleted_at_column_to_posts_tables --table=posts


資料夾:database/migrations裡面多一個檔案



檔名:日期_編號_add_deleted_at_column_to_posts_tables.php



<?php

//檔案:日期_編號_add_deleted_at_column_to_posts_tables.php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddDeletedAtColumnToPostsTables extends Migration
{
/**
* Run the migrations.
*
* @return void
*/

public function up()
{
Schema::table('posts', function (Blueprint $table) {
//
});
}

/**
* Reverse the migrations.
*
* @return void
*/

public function down()
{
Schema::table('posts', function (Blueprint $table) {
//
});
}
}


 





 



<?php
//檔案:日期_編號_add_deleted_at_column_to_posts_tables.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddDeletedAtColumnToPostsTables extends Migration
{
public function up()
{
Schema::table('posts', function (Blueprint $table) {

$table->softDeletes();
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('deleted_at');
});
}
}


//下指令
php artisan migrate


資料庫多一個欄位叫deleted_at



<?php
//檔案:app/post.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
//parents
{
use SoftDeletes;
protected $dates=['deleted_at'];
protected $fillable = ['title','content'];
}


//檔案:routes/web.php

use App\Post;

Route::get('/softdelete', function () {
Post::find(7)->delete();
});


瀏覽器輸入:public/softdelete



呈現空白,編號七的文章在資料庫不會被刪掉,而deleted_at這個欄位會寫入時間





 



//檔案:routes/web.php

use App\Post;

Route::get('/readsoftdelete', function () {
$post=Post::withTrashed()->where('id',7)->get();
return $post;
});


瀏覽器輸入readsoftdelete



呈現編號七文章物件(被刪掉那篇)





 



//檔案:routes/web.php

use App\Post;

Route::get('/readsoftdelete', function () {
$post=Post::onlyTrashed()->get();
return $post;
});


瀏覽器輸入readsoftdelete



呈現所有被軟刪除的文章物件





 



withTrashed,會篩選出被軟刪除與沒被刪除的文章(所有文章)



onlyTrashed,只會篩選出被軟刪除的文章(所有文章)





 



//檔案:routes/web.php

use App\Post;

Route::get('/restore',function(){
Post::withTrashed()->where('is_admin',0)->restore();
});


 



瀏覽器輸入:public/restore



呈現空白,資料庫中被軟刪除的文章已經通通回覆






//檔案:routes/web.php

use App\Post;

Route::get('/forcedelete',function(){
Post::onlyTrashed()->where('is_admin',0)->forceDelete();
});


 



瀏覽器輸入:public/forcedelete



呈現空白,資料庫中被軟刪除的文章就被強制刪除





沒有留言:

張貼留言