首页 > 解决方案 > 在所有模型中实施全局范围

问题描述

我们正在开发一个基于 Laravel Spark 的应用程序。作为其中的一部分,我们希望将资源与特定团队联系起来。

我知道我们可以添加一个全局范围,例如:

<?php


namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class TeamScope implements Scope
{
    /**
     * 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->where('team_id', '=',Auth()->user()->currentTeam->id );
    }
}

但根据文档,我们必须将其添加到我们想要限制的每个模型中,如下所示:

protected static function boot()
{
    parent::boot();
    static::addGlobalScope(new TeamScope);
}

我的问题是可以创建未来的模型而忘记应用此代码。哪个会给我们带来安全漏洞?

有没有办法全面执行范围?

标签: laraveleloquentlaravel-spark

解决方案


我不确定是否有办法全局添加范围。

在我的特定应用程序中,我们不得不为我们的模型添加更多的职责。所以我们创建了一个BaseModel扩展 Laravel 的类Illuminate\Database\Eloquent\Model

然后,所有新模型都扩展了BaseModelLaravel 而不是 Laravel 的模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(new TeamScope);
    }

}

例如:

<?php

namespace App;

class Attribute extends BaseModel
{

}

你也可以有一个特性,你可以使用它来将此范围添加到你的模型中。例如:

trait HasTeamScope
{
    protected static function boot()
        {
            parent::boot();
            static::addGlobalScope(new TeamScope);
        }
    }
}

...然后您可以轻松地在您的模型中重新使用它。

例如:

<?php

namespace App;

class Attribute extends BaseModel
{
    use HasTeamScope;
}

现在,根据您的问题,您可能还会忘记在第一个实例中扩展 BaseModel 或在创建新模型时在第二个实例中添加 Trait。

为了解决这个问题,您可以轻松地创建一个新命令来生成将使用您自己的存根的模型(它扩展了 BaseModel 或在您创建新模型时添加特征)


推荐阅读