用Laravel 自带的 Eloquent ORM 来实现软删除。
首先在数据迁移文件中添加删除时间字段
./database/migrations/2014_10_12_000000_create_users_table.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create( 'users' , function (Blueprint $table ) { $table ->id(); $table ->string( 'name' ); $table ->string( 'email' )->unique(); $table ->timestamp( 'email_verified_at' )->nullable(); $table ->string( 'password' ); $table ->rememberToken(); $table ->timestamps(); $table ->softDeletes()->comment( '删除时间' ); // 默认添加 deleted_at 字段 }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists( 'users' ); } }; |
执行 php artisan migrate
运行迁移文件
修改对应的数据模型
./app/Models/User.php
1
2
3
4
5
6
7
8
|
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class User extends Model { use SoftDeletes; // 开启软删除 protected $guarded = []; // 不可以注入的字段数据,使用create方法才有效 } |
软删除方法
直接调用delete()
方法或者destroy()
方法即可
1
|
User::destroy( $id ); |
这时候查询的数据自动添加过滤条件 deleted_at = NULL
恢复删除
1
|
User::onlyTrashed()->where( 'id' , $id )->restore(); |
永久删除
直接删除数据
1
|
User::forceDeleted( $id ); |
查询包含已删除的数据
使用 withTrashed()
可以查询出包含已删除的数据
1
|
User::withTrashed()->get(); |
只查询已删除的数据
使用 onlyTrashed()
可以只查询出已删除的数据
1
|
User::onlyTrashed()->get(); |
到此这篇关于PHP Laravel软删除的实现方法介绍的文章就介绍到这了,更多相关PHP Laravel软删除内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://peakxin.blog.csdn.net/article/details/124478318