W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
有時(shí)您可能希望定義一個(gè) scope 可以用于模型的所有查詢中。本質(zhì)上,這也是 Eloquent 的"軟刪除"功能的實(shí)現(xiàn)原理。Global scopes 是通過(guò) PHP traits 的組合以及實(shí)現(xiàn) Illuminate\Database\Eloquent\ScopeInterface
接口來(lái)定義的。
首先,我們需要定義一個(gè) trait。 這里我們用 Laravel 的 SoftDeletes 舉例:
trait SoftDeletes {
/**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
}
如果一個(gè) Eloquent 模型引入了一個(gè) trait ,而這個(gè) trait 中帶有符合 bootNameOfTrait 慣例命名的方法 ,那么這個(gè)方法會(huì)在 Eloquent 模型啟動(dòng)的時(shí)候調(diào)用, 您可以在此時(shí)注冊(cè) global scope ,或者做一些其他您想要的操作。定義的 scope 必須實(shí)現(xiàn) ScopeInterface 接口,這個(gè)接口提供了兩個(gè)方法:apply 和 remove。
apply 方法接受一個(gè) Illuminate\Database\Eloquent\Builder 查詢構(gòu)造器對(duì)象以及它所應(yīng)用的 Model,用來(lái)添加這個(gè) scope 所需的額外的 where 子句。而remove 方法同樣接受一個(gè) Builder 對(duì)象以及 Model ,用來(lái)反向的執(zhí)行 apply 操作。也就是說(shuō),remove 方法應(yīng)該移除已經(jīng)添加的 where 子句 (或者其他查詢子句)。因此,我們的 SoftDeletingScope 的方法應(yīng)該如下:
/**
* 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());
$this->extend($builder);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function remove(Builder $builder, Model $model)
{
$column = $model->getQualifiedDeletedAtColumn();
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where)
{
// If the where clause is a soft delete date constraint, we will remove it from
// the query and reset the keys on the wheres. This allows this developer to
// include deleted model in a relationship result set that is lazy loaded.
if ($this->isSoftDeleteConstraint($where, $column))
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
}
}
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: