说,我有5个系统(让我们称之为) .
每个系统都有员工 .
当系统#1的员工登录时,我想向他显示仅为系统#1工作的其他员工的列表 .
我想使用全球范围 .
但我找不到注入登录用户的system_id的方法 .
我尝试了匿名全局范围 - 但静态启动不能接受system_id:
protected static function boot()
{
//this will not work, as scope method is static
$userId = auth()->user()->system_id;
parent::boot();
static::addGlobalScope('thisSystemUser', function (Builder $builder) use($userId) {
$builder->where('system_id', $userId);
});
}
我还尝试了具有单独类的全局范围 - 同样的问题:
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class SystemEmployeeScope 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)
{
// no luck here as well
$userId = auth()->user()->system_id;
/**
* appended query constraint for this scope
*/
$builder->where('system_id', $userId);
}
}
我尝试使用$ model - 无济于事 . 它返回空模型 . 任何试图通过$ model获得一些数据的尝试也都有所收获 .
I do not want to 使用本地范围或动态范围,因为它们不是我想要实现的,并且有更好的方法,在我的情况下使用这些,例如:直接关系到关系 - 在我的情况下多对多 .
有什么办法,我不知道并且不太复杂,不能将system_id塞入范围?
1 回答
你可以这样做 .