讨论数量:
你可能是从哪里看到null值对mysql查询性能有影响改成这样的吧,其实5.7以上版本已经对is null做了优化,这个你可以参考更新,如果仅仅是软删除的话其实查询影响不大,null只有范围搜索可能有一定的影响,而且有各种诡异情况发生,仅仅是 whereNull whereNotNull其实没什么性能隐患,你可以单表几亿条做下测试
重写类
class SoftDeletingScope extends \Illuminate\Database\Eloquent\SoftDeletingScope
{
public function apply(Builder $builder, Model $model)
{
$builder->where($model->getQualifiedDeletedAtColumn(), 0);
}
在模型中 BOOT
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
我们之前也是这个问题,团队定义时间都得是时间戳,然后我找了一下包,发现也就俩文件,就没require进来。自己翻laravel代码,重写了两个文件,SoftDeletes(trait)和SoftDeletingScope(class),这俩文件里把所有是whereNull
的地方改成where($model->getQualifiedDeletedAtColumn(), '=', 0)
,因为你既然要用软删除,肯定还要用“查询被软删除的模型”,比如“包括被软删除的模型withTrashed()
”,“只检索被软删除的模型onlyTrashed()
”,“恢复被软删除的模型restore()
”等等,这些肯定都要改
然后定义了个BaseModel
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Handlers\VSoftDeletes;
abstract class BaseModel extends Model
{
// 软删除
use VSoftDeletes;
// 设置日期时间格式
public $dateFormat = 'U';
protected $dates = [
'created_at',
'updated_at',
'deleted_at',
];
}
推荐文章: