【问题标题】:How do I use Laravel Query Global Scopes如何使用 Laravel 查询全局范围
【发布时间】:2020-07-17 04:07:51
【问题描述】:

我正在按照here 的文档实施 Laravel Global Scope,但这似乎对我不起作用。下面是我在User.php模型中的代码行

<?php

namespace App;

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

class User extends Model
{
    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('age', function (Builder $builder) {
            $builder->where('age', '>' , 100);
        });
    }
}

当我解雇User::all() 时,它只给我用户查询select * from users

如果我做错了什么或遗漏了什么,请告诉我...

【问题讨论】:

  • User 指的是App\User 你在哪里使用User::all()
  • 是的。 Eloquent 返回数据但不添加 where 条件
  • 您是否有机会使用 Tinker?如果是,并且在打开 Tinker 会话后保存了文件 (User.php),则需要先退出并重新启动它。修补匠我的意思是php artisan tinker
  • 你必须在方法的开头调用parent::boot()
  • @AmirAsyraf 不,我没有使用任何修补程序。这只是正常的路由控制器调用

标签: php laravel laravel-6 global-scope


【解决方案1】:

我终于发现自己犯了什么错误。如果有人这样做,请检查以下详细信息。

正如问题中提到的,我使用的是 Laravel 6.x,但我指的是 Laravel 7.x,它有很大的不同。 在 Laravel 6.x 中我们使用

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

在 Laravel 7.x 中我们使用

protected static function booted(){
   static::addGlobalScope(new BlockedUserScope);
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-11-23
  • 2023-03-09
  • 2016-04-14
  • 2017-12-17
  • 2020-05-16
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多