简体   繁体   中英

Remove categories with all childs derived from parent category

I want to remove all related child categories from parent categories. I think I need a recursive function to solve this. Here is my attempt:

public function destroy(Request $request)
{
    $categories = \App\Categories::select('parent_id')->whereNotNull('parent_id')->get();

    foreach ($categories as $category) {
       if ($category->parent_id == $request->cid) {
           $childCategories = \App\Categories::select('parent_id')->where('parent_id', $category->parent_id)->get();

       }
    }

}

My table is like this

+-------------+----------+-----------+
|  id         | name     | parent_id |
+-------------+----------+-----------+
|  1          | MAIN     |   NULL    |
+-------------+----------+-----------+
|  2          | CHILD    |     1     |
+-------------+----------+-----------+
|  3          | CHILD 2  |     2     |
+-------------+----------+-----------+

My expectation:

If I removed the main category, child and child 2 categories have to be removed.

How can I perform this with eloquent?

The answers are ok but it didn't work as I expected. I want to delete all of the sub-categories and its derivates. Given examples are only find the first node.

SOLUTION

I fixed this problem via migrations.

I created a FOREIGN KEY for PARENT_ID which refers to the id of category in migration file. When I perform deleting action it's removing itself with child nodes(It works also in case of its children nodes has children nodes).

Here is the migration code that I used:

$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade'); Then

App\\Categories::find($id)->delete(); removed with child nodes.

You need to check for child category's child entries too. Will you have data further deep?

Better if you repeat

foreach ($categories as $category) {

inside too with the child category to find if child exist inside.

I fixed this problem via migrations.

I created a FOREIGN KEY for PARENT_ID which refers to the id of category in migration file. When I perform deleting action it's removing itself with child nodes(It works also in case of its children nodes has children nodes).

Here is the migration code that I used:

$table->foreign('parent_id')->references('id')->on('categories')->onDelete('cascade');

Then

App\\Categories::find($id)->delete(); removed with child nodes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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