【问题标题】:How to check if any of the parent status is false in category hierarchy while query?查询时如何检查类别层次结构中的任何父状态是否为假?
【发布时间】:2021-10-18 07:29:34
【问题描述】:

我在层次结构中有一个类别模块。我需要通过检查是否有任何一个父母不应该处于非活动状态(假)来查询该类别。

例如

  1. 第一类(非活动或错误) 1.1 > 第一类子 1.1.1> 第一类 Grand Child

我的查询

$category = Category::where('status',true)->where('title','like','%'.$keywords.'%')->paginate(10);

这个查询只检查它的状态是真还是假。但我也需要检查其父级别的状态。 那么,有没有办法在查询中检查父级状态。该类别可能有父级,也可能没有父级。因此,因此 whereHas('parents') 不起作用。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    有,假设您的类别模型看起来像这样。

    class Category extends Model {
        public function parent() {
            return $this->belongsTo(self::class, 'parent_id');
        }
    }
    

    然后您可以使用whereHas(),提供一个闭包来检查您的条件并查询您在该关系中的条件。处理没有父母的情况,检查它是否有正确状态的父母或没有父母。

    Category::where('status',true)
        ->where(funcion ($query) {
            $query->whereHas('parent', function ($query) {
                $query->where('status', true);
            })->orDoesntHave('parent');
        })->get();
    

    对于多重嵌套,您可以通过不断添加条件来解决它。它不是最优的,但在查询时你不知道嵌套。

    ->where(funcion ($query) {
        $query->whereHas('parent.parent', function ($query) {
            $query->where('status', true);
        })->orDoesntHave('parent.parent');
    })->where(funcion ($query) {
        $query->whereHas('parent.parent.parent', function ($query) {
            $query->where('status', true);
        })->orDoesntHave('parent.parent.parent');
    })
    

    从长远来看,另一种解决方案可能是制定逻辑,在所有类别的状态发生变化时递归地更新状态。

    【讨论】:

    • 非常感谢!它确实有效,但您介意“我如何检查所有父母?我的意思是查询中父母身份的父母”?我想我需要在 where 条件下进行递归。
    • 虽然有点意思,但是你有最大嵌套级别吗?
    • 最大可达 5
    • 假设它最多可以达到 5,我已经重复了其中的条件。感谢您的宝贵时间
    • 我已经更新了我的答案,并提出了建议。
    【解决方案2】:

    您可以通过提供关系名称来使用 whereHas 方法:

    $category = Category::where('status',true)->whereHas('parent', function ($q) {
    $q->where('status', true)->whereHas('parent', function ($query) {
    $query->where('status', true)});
    })->where('title','like','%'.$keywords.'%')->paginate(10);
    

    【讨论】:

    • 如果我在父级查询,whereHas 不起作用。它可以工作,但即使其状态为 true 也不显示
    • 你的意思是检查父母状态的父母吗?
    • 是的,检查一个类别的所有父母状态
    • 我已经更新了代码试试看
    • 有点解决了我的问题。感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 2021-01-08
    • 2018-01-21
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多