一文了解laravel模型删除和软删除

1、删除模型
1.1 使用delete删除模型
删除模型很简单,先获取要删除的模型实例,然后调用delete方法即可:
$post = Post::find(5); if($post->delete()){ echo '删除文章成功!'; }else{ echo '删除文章失败!'; }该方法返回true或false。
1.2 使用destroy删除模型
当然如果已知要删除的模型id的话,可以用更简单的方法destroy直接删除:
$deleted = Post::destroy(5);
你也可以一次传入多个模型id删除多个模型:
$deleted = Post::destroy([1,2,3,4,5]);
调用destroy方法返回被删除的记录数。
1.3 使用查询构建器删除模型
既然前面提到Eloquent模型本身就是查询构建器,也可以使用查询构建器风格删除模型,比如我们要删除所有浏览数为0的文章,可以使用如下方式:
$deleted = Models\Post::where('views', 0)->delete();返回结果为被删除的文章数。
2、软删除实现
上述删除方法都会将数据表记录从数据库删除,此外Eloquent模型还支持软删除。
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { use SoftDeletes; //设置表名 public $table = 'posts'; //设置主键 public $primaryKey = 'id'; //设置日期时间格式 public $dateFormat = 'U'; protected $guarded = ['id','views','user_id','updated_at','created_at']; protected $dates = ['delete_at']; }然后对应的数据库posts中添加deleted_at列,我们使用迁移来实现,先执行Artisan命令:
php artisan make:migration alter_posts_deleted_at --table=posts
然后编辑生成的PHP文件如下:
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterPostsDeletedAt extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('posts', function (Blueprint $table) { $table->softDeletes(); }); } ...//其它方法 }然后运行:
php artisan migrate
这样posts中就有了deleted_at列。接下来,我们在控制器中编写测试代码:
$post = Post::find(6); $post->delete(); if($post->trashed()){ echo '软删除成功!'; dd($post); }else{ echo '软删除失败!'; }那如果想要在查询结果中包含软删除的记录呢?可以使用SoftDeletes trait上的withTrashed方法:
$posts = Post::withTrashed()->get(); dd($posts);
有时候我们只想要查看被软删除的模型,这也有招,通过SoftDeletes上的onlyTrashed方法即可:
$posts = Post::onlyTrashed()->get(); dd($posts);
软删除恢复
有时候我们需要恢复被软删除的模型,可以使用SoftDeletes提供的restore方法:
恢复单个模型
$post = Post::find(6); $post->restore();
有点问题,ID为6的已经被软删除了,Post::find(6) 是查不到数据的,
应该
$post = Post::withTrashed()->find(6); $post->restore();
恢复多个模型
Post::withTrashed()->where('id','>',1)->restore();恢复所有模型
Post::withTrashed()->restore();
恢复关联查询模型
$post = Post::find(6); $post->history()->restore();
强制删除
如果模型配置了软删除但我们确实要删除改模型对应数据库表记录,则可以使用SoftDeletes提供的forceDelete方法:
$post = Post::find(6); $post->forceDelete();
PHP中文网,大量的免费laravel入门教程,欢迎在线学习!
本文转自:https://blog.csdn.net/weixin_38112233/article/details/78574007
以上就是一文了解laravel模型删除和软删除的详细内容,更多内容请关注技术你好其它相关文章!
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场