我這邊使用的Laravel的ORM。經(jīng)常用的軟刪除字段。但是Laravel的軟刪除字段默認(rèn)值null。我不知道這個(gè)走了索引沒(méi)?所以有沒(méi)有大佬改造過(guò)laravel的ORM繼承軟刪除類(lèi)的。把他查詢(xún)默認(rèn)查詢(xún)?yōu)?,以及字段類(lèi)型為int
還是記錄下吧。
修改方案。
在模型文件增加一個(gè)方法。要重寫(xiě) SoftDeletingScope 這個(gè)
/**
* 模型日期的存儲(chǔ)格式
*
* @var string
*/
protected $dateFormat = 'U';
use SoftDeletes;
public static function bootSoftDeletes(): void
{
static::addGlobalScope(new SoftDeletingScope());
}
<?php
namespace app\common\model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope as SystemSoftDeletingScope;
class SoftDeletingScope extends SystemSoftDeletingScope
{
/**
* 未刪除的默認(rèn)值.
*/
const NOT_DELETE_DEFAULT_VALUE = 0;
/**
* Apply the scope to a given Eloquent query builder.
* Filter soft deleted data by default
*
* @param Builder $builder
* @param Model $model
*
* @return void
*/
public function apply(Builder $builder, Model $model): void
{
$builder->where($model->getQualifiedDeletedAtColumn(), self::NOT_DELETE_DEFAULT_VALUE);
}
/* Add the restore extension to the builder.
* Add restore extensions to restore soft deleted data back to normal data
*
* @param IlluminateDatabaseEloquentBuilder $builder
*
* @return void
*/
protected function addRestore(Builder $builder)
{
$builder->macro('restore', function (Builder $builder) {
$builder->withTrashed();
return $builder->update([$builder->getModel()->getDeletedAtColumn() => self::NOT_DELETE_DEFAULT_VALUE]);
});
}
/**
* Add the without-trashed extension to the builder.
* Filtering data that has been soft deleted
*
* @param Builder $builder
*
* @return void
*/
protected function addWithoutTrashed(Builder $builder): void
{
$builder->macro('withoutTrashed', function (Builder $builder) {
$model = $builder->getModel();
$builder->withoutGlobalScope($this)->where($model->getQualifiedDeletedAtColumn(),
self::NOT_DELETE_DEFAULT_VALUE);
return $builder;
});
}
/**
* Add the only-trashed extension to the builder.
* Add an extension to retrieve only data that has been soft deleted
*
* @param Builder $builder
*
* @return void
*/
protected function addOnlyTrashed(Builder $builder): void
{
$builder->macro('onlyTrashed', function (Builder $builder) {
$model = $builder->getModel();
$builder->withoutGlobalScope($this)->where($model->getQualifiedDeletedAtColumn(), '!=',
self::NOT_DELETE_DEFAULT_VALUE);
return $builder;
});
}
}
何必那么麻煩,直接:
$this->model->query()->whereIn('id', $idArrary)->update([
'delete_time' => date('Y-m-d H:m:s')
]);
軟刪除查詢(xún)是要帶上這個(gè)條件,加上索引后,你說(shuō)datetime類(lèi)型快還是int類(lèi)型快呢。當(dāng)然你也可以不加索引,我?guī)湍銣y(cè)試了 count統(tǒng)計(jì)時(shí)候 15w數(shù)據(jù) 不走索引 1.2s,走了索引0.04s