以最简单的代码为例引出具体内容
软删除具体设置方法使用看官方文档
$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
类中的boo
t开头的方法,看一下 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
属性里塞值
- 终
如有不对的地方请及时指正