[英]Laravel Approved Categories get in same table
Laravel version: 7.0 Laravel 版本:7.0
This is my categories
table.这是我的
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();
});
There are two levels of categories.有两个级别的类别。 If
parent_id
is 0
, then that is category
, if parent_id
isn't 0
, then that is subcategory
.如果
parent_id
为0
,则为category
,如果parent_id
不为0
,则为subcategory
。
I want to get all categories & subcategories
which have status == 1
& if it's subcategory
, then its parent category's status
should be 1
.我想获取所有具有
status == 1
的categories & subcategories
,如果它是subcategory
,那么它的parent category's status
应该是1
。
I made Category
model.我制作了
Category
model。
$categories = Category::where('status', 1)->get();
Above query could get subcategories which the parent category's status == 0
.上面的查询可以获得
parent category's status == 0
的子类别。 How can I filter all categories & subcategories?如何过滤所有类别和子类别? Can any one help me?
谁能帮我?
You can split the task into two.您可以将任务一分为二。
$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();
Remember that PHP closures works as ( )
in SQL.请记住,PHP 闭包在 SQL 中用作
( )
。 So the above reads as:所以上面写成:
(parent_id = 0 AND status = 1)
OR
(parent_id != 0 AND status = 1 AND (sub query that does a count > 0))
They are needed since we are using the orWhere
.因为我们使用的是
orWhere
,所以需要它们。
The part you were missing were probably the whereHas
.您缺少的部分可能是
whereHas
。 That lets you query a relation.这使您可以查询关系。 In my example above I assume the inverse
belongsTo
relationship is set up on your Category
model as parent()
.在上面的示例中,我假设在您的
Category
model 上设置了反向的belongsTo
关系作为parent()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.