繁体   English   中英

Laravel 批准类别进入同一张表

[英]Laravel Approved Categories get in same table

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 model。

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

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

您可以将任务一分为二。

  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 model 上设置了反向的belongsTo关系作为parent()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM