dcat/laravel-softdeletes

Laravel ORM softDeletes

1.0.1 2021-01-18 06:42 UTC

This package is auto-updated.

Last update: 2024-04-18 13:26:44 UTC


README

68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d3733383944382e7376673f7374796c653d666c6174 StyleCI 68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6a716870682f6c61726176656c2d736f667464656c657465732e7376673f636f6c6f723d343039394445 68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d372b2d3539613966382e7376673f7374796c653d666c6174

Laravel softdeletes是一个用于替代Laravel内置的软删除softDelets功能的扩展包,可以把软删数据存储到独立的数据表中,从而不影响给原始表字段增加唯一索引,且可以起到提升性能的作用。

环境

  • PHP >= 7
  • laravel >= 5.5

安装

composer require dcat/laravel-softdeletes

简介

Laravel内置的softDelets功能会把软删的数据和正常数据存在同一个数据表中,这样会导致数据表的字段无法直接添加unique索引,因为很容易产生冲突,这样会给实际业务开发带来诸多不必要的困扰。 而Laravel softdeletes则可以把软删数据存储到独立的数据表中,从而不影响给原始表字段增加唯一索引,且可以起到提升性能的作用。

使用

首先需要创建两张字段一模一样的数据表,并且两张表都需要添加deleted_at字段

// 文章表
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();
});

模型定义如下,默认的软删除表表名为:{原始表}_trash,如上面的posts表的默认软删除表表名是posts_trash

<?php

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;
    }
}

除了withTrashed只能用于查询数据之外,其他方法的使用与Laravel内置的软删除功能完全一致,下面是简单的用法示例

需要注意withTrashed只能用于查询数据,不能用于updatedelete!!!

查询正常表数据

$posts = Post::where(...)->get();

仅查询软删除表数据 (onlyTrashed)

$trashedPosts = Post::onlyTrashed()->where(...)->get();

同时查询正常和软删数据 (withTrashed),需要注意withTrashed只能用于查询数据,不能用于updatedelete!!!

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();

License

The MIT License (MIT).