【问题标题】:Laravel 5 Global Scope: injecting variableLaravel 5 Global Scope:注入变量
【发布时间】:2018-08-17 13:49:38
【问题描述】:

比如说,我有 5 个系统(让我们这么称呼它们吧)。

每个系统都有员工。

当系统 #1 的员工登录时,我想向他显示仅为系统 #1 工作的其他员工的列表。

我想使用全局范围。

但我找不到注入登录用户的 system_id 的方法。

我尝试了匿名全局范围 - 但静态启动确实不能接受 system_id:

受保护的静态函数 boot() { //这不起作用,因为范围方法是静态的 $userId = auth()->user()->system_id; 父::boot(); static::addGlobalScope('thisSystemUser', function (Builder $builder) use($userId) { $builder->where('system_id', $userId); }); }

我还尝试了具有单独类的全局范围 - 同样的问题:

命名空间应用\范围; 使用 Illuminate\Database\Eloquent\Builder; 使用 Illuminate\Database\Eloquent\Model; 使用 Illuminate\Database\Eloquent\Scope; 类 SystemEmployeeScope 实现范围 { /** * 将范围应用于给定的 Eloquent 查询构建器。 * * @param \Illuminate\Database\Eloquent\Builder $builder * @param \Illuminate\Database\Eloquent\Model $model * @return 无效 */ 公共函数应用(生成器 $builder,模型 $model) { // 这里也没有运气 $userId = auth()->user()->system_id; /** * 附加此范围的查询约束 */ $builder->where('system_id', $userId); } }

我尝试使用 $model - 无济于事。它返回空模型。任何通过 $model 获取一些数据的尝试也失败了。

我不想使用本地范围或动态范围,因为它们不是我想要完成的并且有更好的方法,在我的情况下使用它们,例如:条件直接关系 - 在我的情况下是多对多。

有什么方法,我不知道也不太复杂,可以将 system_id 塞进范围?

【问题讨论】:

  • 你使用的是哪个版本的 Laravel?
  • 抱歉迟到了 - 不同的时区和 TGIF :) L5.6

标签: laravel scope laravel-eloquent


【解决方案1】:

你可以这样做。

namespace App\Scopes;

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

class SystemEmployeeScope implements Scope
{

    private $user;

    public function __construct()
    {
        $this->user = auth()->user();
    }

    public function apply(Builder $builder, Model $model)
    {
        $userId = $this->user->id
        $builder->where('system_id', $userId);
    }
}

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2015-05-17
    • 2019-10-22
    • 1970-01-01
    • 2016-04-11
    • 2015-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多