软删除的性能比直接delete要好,而且更容易恢复误删除的数据,在开发上一般采用软删除。
laravel框架自带的model是直接执行delete操作,但是可以通过简单的代码把它设置为软删除,需要做到以下2点:
1)设置查询作用域
参考文档:https://docs.golaravel.com/docs/5.6/eloquent/#query-scopes
2)删除动作设置为更新(使用is_deleted=1标识为已删除)
废话不说,贴上代码,可参考我github一个学习性项目:https://github.com/lizhibin205/my-admin/tree/master/admin/app/Utils
查询作用域
<?php
namespace App\Utils;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class SoftDeletingScope implements Scope
{
/**
* 把约束加到 Eloquent 查询构造中.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('is_deleted', '=', 0);
}
}
删除动作设置为更新
<?php
namespace App\Utils;
trait SoftDeletes
{
/**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
/**
* Get the name of the "deleted at" column.
* 返回软删除的标记字段
* @return string
*/
public function getDeletedAtColumn()
{
return 'is_deleted';
}
/**
* Get the fully qualified "deleted at" column.
* 获取删除字段名称,qualifyColumn会只能补充表的名称
* @return string
*/
public function getQualifiedDeletedAtColumn()
{
return $this->qualifyColumn($this->getDeletedAtColumn());
}
/**
* Perform the actual delete query on this model instance.
*
* @return mixed
*/
protected function performDeleteOnModel()
{
return $this->runSoftDelete();
}
/**
* Perform the actual delete query on this model instance.
*
* @return void
*/
protected function runSoftDelete()
{
$query = $this->newModelQuery()->where($this->getKeyName(), $this->getKey());
$columns = [$this->getDeletedAtColumn() => 1];
if ($query->update($columns)) {
$this->syncOriginal();
}
}
}
应用到model,非常简单
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Utils\SoftDeletes;
class Article extends Model
{
use SoftDeletes;
//
protected $table = 'article';
}