
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模子还支撑软删除。
所谓软删除指的是数据表纪录并未真的从数据库删除,而是将表纪录的标识状况标记为软删除,如许在查询的时刻就能够加以过滤,让对应表纪录看上去是被”删除“了。Laravel中运用了一个日期字段作为标识状况,这个日期字段能够自定义,这里我们运用deleted_at,假如对应模子被软删除,则deleted_at字段的值为删除时候,不然该值为空。
要让Eloquent模子支撑软删除,还要做一些设置。首先在模子类中要运用SoftDeletestrait,该trait为软删除供应一系列相干要领,细致可参考源码Illuminate\Database\Eloquent\SoftDeletes,另外还要设置$date属性数组,将deleted_at置于个中:
<?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();
ki4网,大批的免费laravel入门教程,迎接在线进修!
本文转自:https://blog.csdn.net/weixin_38112233/article/details/78574007
以上就是一文相识laravel模子删除和软删除的细致内容,更多请关注ki4网别的相干文章!