加强所有模型的全球范围

时间:2019-01-29 13:56:18

标签: laravel eloquent laravel-spark

我们正在开发基于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);
}

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

有没有办法全面实施范围?

3 个答案:

答案 0 :(得分:0)

您可以使用将来的模型可以扩展的所需全局范围来创建自己的基本模型。

答案 1 :(得分:0)

您应该使用启动功能创建特征。性格名为BelongsToTeam。

并且在所有模型中仅添加:使用BelongsToTeam;

答案 2 :(得分:0)

我不确定是否可以全局添加范围。

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

所有新模型然后扩展BaseModel而不是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。

要解决此问题,您可以轻松地create a new command to produce models使用您自己的存根(扩展BaseModel或在创建新模型时添加特征)

相关问题