Global Scopes

2018-02-24 15:52 更新

有時(shí)您可能希望定義一個(gè) scope 可以用于模型的所有查詢中。本質(zhì)上,這也是 Eloquent 的"軟刪除"功能的實(shí)現(xiàn)原理。Global scopes 是通過 PHP traits 的組合以及實(shí)現(xiàn) Illuminate\Database\Eloquent\ScopeInterface 接口來定義的。

首先,我們需要定義一個(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í)注冊 global scope ,或者做一些其他您想要的操作。定義的 scope 必須實(shí)現(xiàn) ScopeInterface 接口,這個(gè)接口提供了兩個(gè)方法:apply 和 remove。

apply 方法接受一個(gè) Illuminate\Database\Eloquent\Builder 查詢構(gòu)造器對象以及它所應(yīng)用的 Model,用來添加這個(gè) scope 所需的額外的 where 子句。而remove 方法同樣接受一個(gè) Builder 對象以及 Model ,用來反向的執(zhí)行 apply 操作。也就是說,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);
        }
    }
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號