【问题标题】:laravel scopes with relation and conditions具有关系和条件的 laravel 范围
【发布时间】:2019-10-12 01:16:10
【问题描述】:

我有这个 laravel 作用域代码

public function apply(Builder $builder, Model $model)
{
    $builder->whereDoesntHave('getPermissionData');
}

到目前为止一切正常,我需要的是调整条件 像这样

public function apply(Builder $builder, Model $model)
{
    /*
        if($builder->whereHas('getPermissionData'))
        {
            check the relation 
            and do some code here
        }
    */
    $builder->whereDoesntHave('getPermissionData');
}

有没有可能

【问题讨论】:

  • 你能解释一下你的最终目标是什么吗?可能有更好的方法来实现您的目标。
  • 我想检查用户是否有权查看项目以及脚本中很多地方的项目关系,所以在获取项目之前我想检查用户是否有权查看项目
  • 我有权限表,如管理员用户编辑器等。我有一个名为 permission_items 的表,它有两列 permission_item_item_id 和 permission_item_permission_id 并且每个身份验证用户都有一个权限,所以我想检查用户是否有权查看该项目与否

标签: php laravel scope


【解决方案1】:

您需要在or 中相互创建两个不同的条件。您还应该将此条件包装在 where 子句中,这样下一个条件也不会出现在 or 中

public function apply(Builder $builder, Model $model) {
    $builder->where(function ($query) {
         $query->whereDoesntHave('getPermissionData')
               ->orWhereHas('getPermissionData', function ($permissionQuery) {
                   // Apply your condition to the relation query
               });
    });
}

【讨论】:

猜你喜欢
  • 2021-03-10
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2022-09-23
  • 2021-12-12
  • 2020-10-24
  • 2020-04-17
相关资源
最近更新 更多