本文实例讲述了Laravel5.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件事情:
首先我们做第一步和第二步:
<?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();
}
更多关于Laravel相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。