使用Laravel5.1 框架怎么实现模型软删除操作?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
1 普通删除
在软删除之前咱先看看普通的删除方法:
public function getDelete()
{
Article::destroy(1);
Article::destroy([1,2,3]);
}
public function getDelete()
{
$article = Article::find(3);
$article->delete();
}
public function getDelete()
{
// 返回一个整形 删除了几条数据
$deleteRows = Article::where('id','>',3)->delete();
dd($deleteRows); // 2
}
如果你要实现软删除 你应该提前做3件事情:
添加deleted_at 到模型的 $date 属性中。
在模型中使用 Illuminate\Database\Eloquent\SoftDeletes 这个trait
保证你的数据表中有deleted_at列 如果没有就添加这个列。
首先我们做第一步和第二步:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
// 使用SoftDeletes这个trait
use SoftDeletes;
// 白名单
protected $fillable = ['title', 'body'];
// dates
protected $dates = ['deleted_at'];
}
然后我们生成一个迁移文件来增加deleted_at列到数据表:
class InsertDeleteAtIntroArticles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('articles', function (Blueprint $table) {
$table->dropSoftDeletes();
});
}
}
现在我们就可以删除一条数据试试啦:
public function getDelete()
{
$article = Article::first();
$article->delete();
}
↑ 当我们删了这条数据后 在数据表中的表示是 deleted_at 不为空 它是一个时间值,当delete_at不为空时 证明这条数据已经被软删除了。
if ($article->trashed()){
echo '这个模型已经被软删除了';
}
有一点需要注意,当数据被软删除后 它会自动从查询数据中排除、就是它无法被一般的查询语句查询到。当我们想要查询软删除数据时 可以使用withTrashed方法
public function getIndex()
{
$article = Article::withTrashed()->first();
if ($article->trashed()){
echo '被软删除了'; // 代码会执行到这一行
}
}
我们还可以使用onlyTrashed,它和withTrashed的区别是 它只获得软删除的数据。
public function getIndex()
{
$articles = Article::onlyTrashed()->where('id','<','10')->get()->toArray();
dd($articles);
}
public function getIndex()
{
$article = Article::withTrashed()->find(6);
$article->restore();
}
public function getIndex()
{
$article = Article::withTrashed()->find(6);
$article->forceDelete();
}
关于使用Laravel5.1 框架怎么实现模型软删除操作问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。