软删除源码分析

以最简单的代码为例引出具体内容

软删除具体设置方法使用看官方文档

$user = User::find(1);

打印sql
“select * from admin_users where admin_users.id = ? and admin_users.deleted_at is null limit 1”
可知是在sql语句中加入is null 进行判断,打印查询构造器中的wheres属性

array:2 [0 => array:5 ["type" => "Basic"
    "column" => "admin_users.id"
    "operator" => "="
    "value" => 1
    "boolean" => "and"
  ]
  1 => array:3 ["type" => "Null"
    "column" => "admin_users.deleted_at"
    "boolean" => "and"
  ]
]

原理就是 往wheres属性中增加相应的信息,看下Model类的构造函数

<?php

    /**
     * Create a new Eloquent model instance.
     *
     * @param  array  $attributes
     * @return void
     */
    public function __construct(array $attributes = [])
    {

        $this->bootIfNotBooted();

        $this->syncOriginal();

        $this->fill($attributes);
    }

构造函数中·bootIfNotBooted·中会调用该类中的·boot·方法

    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        static::bootTraits();
    }

    /**
     * Boot all of the bootable traits on the model.
     *
     * @return void
     */
    protected static function bootTraits()
    {
        $class = static::class;

        foreach (class_uses_recursive($class) as $trait) {
            if (method_exists($class, $method = 'boot'.class_basename($trait))) {

                forward_static_call([$class, $method]);
            }

        }
    }

最终会调用所有traits 类中的boot开头的方法,看一下 trait
SoftDeletes 下的bootSoftDeletes方法

    /**
     * Boot the soft deleting trait for a model.
     *
     * @return void
     */
    public static function bootSoftDeletes()
    {

        static::addGlobalScope(new SoftDeletingScope);
    }

这边是注册一个全局作用域,最后会调用Illuminate\Database\Eloquent SoftDeletingScope类下的apply方法

    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {


        $builder->whereNull($model->getQualifiedDeletedAtColumn());

    }

这边就一目了然了,最终就是往查询构造器的wheres属性里塞值

如有不对的地方请及时指正

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值