PHP code example of dcat / laravel-softdeletes
1. Go to this page and download the library: Download dcat/laravel-softdeletes library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dcat / laravel-softdeletes example snippets
// 文章表
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title')->nullable();
$table->string('body')->nullable();
// 两张表都需要删除时间字段
$table->timestamp('deleted_at')->nullable();
$table->timestamps();
});
// 文章软删除表
Schema::create('posts_trash', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title')->nullable();
$table->string('body')->nullable();
// 两张表都需要删除时间字段
$table->timestamp('deleted_at')->nullable();
$table->timestamps();
});
namespace App\Models;
use Dcat\Laravel\Database\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use SoftDeletes;
/**
* 自定义软删除表表名,默认为 {$table}_trash
*
* @var string
*/
protected $trashedTable = 'posts_trash';
/**
* 自定义软删除表表名,如有需要可以重写此方法
*
* @return mixed
*/
public function getTrashedTable()
{
return $this->trashedTable;
}
}
$posts = Post::where(...)->get();
$trashedPosts = Post::onlyTrashed()->where(...)->get();
Post::withTrashed()
->where(...)
->offset(5)
->limit(5)
->get();
// 可以使用子查询以及whereHas等
Post::withTrashed()
->whereHas('...', function ($q) {
$q->where(...);
})
->offset(5)
->limit(5)
->get();
// 分页
Post::withTrashed()
->whereHas('...', function ($q) {
$q->where(...);
})
->paginate(10);
$post = Post::first();
// 软删除
$post->delete();
// 还原
$post->restore();
// 硬删
$post->forceDelete();
// 批量软删
Post::where(...)->delete();
// 批量硬删
Post::onlyTrashed()->where(...)->delete();