【问题标题】:Laravel Approved Categories get in same tableLaravel 批准的类别在同一张表中
【发布时间】:2020-10-29 12:38:40
【问题描述】:

Laravel 版本:7.0

这是我的categories 表。

        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('parent_id')->default(0);
            $table->string('name');
            $table->boolean('status')->default(1);
            $table->timestamps();
        });

有两个级别的类别。 如果parent_id0,那么就是category,如果parent_id 不是0,那么就是subcategory

我想获取所有具有status == 1categories & subcategories,如果是subcategory,那么它的parent category's status 应该是1

我制作了Category 模型。

$categories = Category::where('status', 1)->get();

上面的查询可以获得parent category's status == 0的子类别。 如何过滤所有类别和子类别? 谁能帮帮我?

【问题讨论】:

    标签: php mysql laravel eloquent laravel-query-builder


    【解决方案1】:

    您可以将任务一分为二。

    1. 获取所有类别(status = 1 和 parent_id = 0)
    2. 获取所有子类别(status = 1 and parent_id != 0 and parent.status = 1)
    $categories = Category::query()
        // 1.
        ->where(function ($query) {
            $query->whereStatus(1)->whereParentId(0);
        })
        // 2.
        ->orWhere(function ($query) {
            $query
                ->where('parent_id', '!=', 0)
                ->whereStatus(1)
                ->whereHas('parent', function ($query) {
                    $query->whereStatus(1);
                });
        })
        ->get();
    

    请记住,PHP 闭包在 SQL 中作为 ( ) 工作。所以上面写成:

    (parent_id = 0 AND status = 1) 
        OR 
    (parent_id != 0 AND status = 1 AND (sub query that does a count > 0))
    

    因为我们使用的是orWhere,所以需要它们。

    您缺少的部分可能是whereHas。这使您可以查询关系。在我上面的示例中,我假设您的 Category 模型上的反向 belongsTo 关系设置为 parent()

    【讨论】:

    • 太棒了,像魅力一样工作!谢谢,orWhere(function $query) 在这里,我们不应该把($query) 吗?
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 2017-02-18
    • 2020-09-08
    • 2015-05-12
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多