【问题标题】:Laravel 5.1 issue implementing global scopeLaravel 5.1 问题实现全局范围
【发布时间】:2016-03-05 15:16:04
【问题描述】:

所以我试图在 laravel 5.1 中创建一个全局范围,但只是继续收到以下错误 Trait 'Eloquent\Scopes\DependentTypeTrait' not found

这是我的代码:

App\Models\Eloquent\Scopes\DependentTypeTrait.php:

<?php namespace App\Models\Eloquent\Scopes;

trait DependentTypeTrait {

    /**
     * Boot the Active Events trait for a model.
     *
     * @return void
     */
    public static function bootDependentTypeTrait()
    {
        static::addGlobalScope(new DependentTypeScope);
    }

}

App\Models\Eloquent\Scopes\DependentTypeScope.php:

<?php namespace App\Models\Eloquent\Scopes;

use Illuminate\Database\Eloquent\ScopeInterface;
use Illuminate\Database\Eloquent\Builder;

class DependentTypeScope implements ScopeInterface
{

    public function apply(Builder $builder)
    {
        $builder->where('vip_type_id', 2);
    }

    public function remove(Builder $builder)
    {

        $query = $builder->getQuery();

        // here you remove the where close to allow developer load
        // without your global scope condition

        foreach ((array) $query->wheres as $key => $where) {

            if ($where['column'] == 'vip_type_id') {

                unset($query->wheres[$key]);

                $query->wheres = array_values($query->wheres);
            }
        }
    }
}

App\Models\Dependent.php:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Eloquent\Scopes\DependentTypeTrait;

class Dependent extends Model
{

    use DependentTypeTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = '<my table name>';

    /**
     * The actual primary key for the model.
     *
     * @var string
     */
    protected $primaryKey = '<my primary key>';

}

我觉得我的命名空间是正确的,但它仍然说它找不到属性....有什么想法吗?

【问题讨论】:

    标签: php laravel scope


    【解决方案1】:

    我认为您在尝试导入 DependentTypeTrait 时使用命名空间错误:

    <?php namespace App\Models\Eloquent\Scopes;
    
    trait DependentTypeTrait { //...
    

    然后你在App\Models\Dependent中使用它:

    use Eloquent\Scopes\DependentTypeTrait;
    

    那些命名空间不匹配。试试这个:

    use App\Models\Eloquent\Scopes\DependentTypeTrait;
    

    或者您可以修改您的 composer.json 以更改 Eloquent 命名空间的自动加载方式:

    "autoload": {
        "psr-4": {
            "Eloquent\\": "app/Models/Eloquent"
        }
    },
    

    别忘了转储你的自动加载器:$ composer dump-autoload

    虽然特别是因为您使用的是 Laravel 中普遍存在的名称 Eloquent,但即使您可以节省一些打字时间,我自己也不会走这条路。 Laravel 本身使用命名空间 Illuminate\Database\Eloquent,所以你现在可能不会发生冲突,但如果 Taylor 改变了一些东西,或者你使用了第三方库来踩它,这种可能性就存在。

    【讨论】:

    • 你是对的!我假设由于模型上的命名空间是 App\Namespace,所以我不必在使用时添加它......
    猜你喜欢
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多