将静态方法添加到我的 Laravel 模型或使特征动态

时间:2021-02-03 08:46:55

标签: php laravel model-view-controller

默认情况下,我使用以下特征将经过身份验证的 user_id 添加到每个查询,但有时我想使用另一个 user_id,因此如果有任何方法可以将该 user_id 添加为参数或其他函数,请帮助我

static::addGlobalScope('user_id', function (Builder $builder) {
$id = null;
$role = auth()->user()->roles;
                
if (auth()->check()) {
    if ($role[0]->id == 1) {
        $id = auth()->id();
    } else {
        $id = auth()->user()->user_id;
    }
}
              
return $builder->where((new self())->getTable() .'.user_id', $id)
               ->orWhere((new self())->getTable() .'.user_id', 0);

});

由于枢轴,我需要使用模型

0 个答案:

没有答案