请教,“如何获取所属分类的父级关系”?(已解决)

傻了,直接在分类表模型中写个获取父节点的方法就可以了,问题已解决。

分类表的结构如下所示(去掉了非关键字段):

CREATE TABLE `common_categories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL DEFAULT '0',
  `order` int(11) NOT NULL DEFAULT '0',
  `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

现有如下分类:

在课程班次表中的所属分类字段category存储的位common_categories表的ID,其表结构如下所示(去掉了非关键字段):

CREATE TABLE `classes` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '班次', 
  `category` int(11) NOT NULL COMMENT '所述分类',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

问题一:在展示课程表内容时如何获取所属分类的父级关系?

我在表中只存储了所选层级的id,现有需求,需要把该层级的父节点以上的节点全部展现出来。
例如:父>父1>父2>子

目前模型关联时这样写的

只能获取到当前分类的信息,记得在社区看到过一个通过递归获取信息的(那个貌似是针对分类表本身递归出树状目录的),自己没有想出怎样写,所以想请教一下各位。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
最佳答案
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $guarded = [];

//    Schema::create('courses', function (Blueprint $table) {
//        $table->id();
//        $table->unsignedInteger('category_id');
//        $table->string('name');
//        $table->timestamps();
//    });

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id')
            ->with('parent');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
//    Schema::create('categories', function (Blueprint $table) {
//        $table->id();
//        $table->unsignedInteger('parent_id');
//        $table->string('name');
//        $table->timestamps();
//    });

    protected $guarded = [];

    public function parent()
    {
        return $this->belongsTo(get_class($this))->with('parent');
    }

    public function child()
    {
        return $this->hasMany(get_class($this), 'parent_id');
    }

    public function children()
    {
        return $this->child()->with('children', 'parent');
    }
}

Route::get('demo', function () {
    \App\Models\Category::insert([
        [
            'parent_id' => 0,
            'name'      => '理学',
        ],
        [
            'parent_id' => 1,
            'name'      => '物理学',
        ],
        [
            'parent_id' => 2,
            'name'      => '天体物理',
        ],
        [
            'parent_id' => 3,
            'name'      => '量子力学',
        ],
    ]);

    \App\Models\Course::insert([
        [
            'category_id' => 4,
            'name'        => '暗物质',
        ],
        [
            'category_id' => 4,
            'name'        => '暗能量',
        ],
    ]);

    return \App\Models\Course::with('category')->first();
});
{
    "id": 1,
    "category_id": 4,
    "name": "暗物质",
    "created_at": null,
    "updated_at": null,
    "category": {
        "id": 4,
        "parent_id": 3,
        "name": "量子力学",
        "created_at": null,
        "updated_at": null,
        "parent": {
            "id": 3,
            "parent_id": 2,
            "name": "天体物理",
            "created_at": null,
            "updated_at": null,
            "parent": {
                "id": 2,
                "parent_id": 1,
                "name": "物理学",
                "created_at": null,
                "updated_at": null,
                "parent": {
                    "id": 1,
                    "parent_id": 0,
                    "name": "理学",
                    "created_at": null,
                    "updated_at": null,
                    "parent": null
                }
            }
        }
    }
}

是这样吗?

3年前 评论
Hi_Debug (楼主) 3年前
讨论数量: 1
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Course extends Model
{
    protected $guarded = [];

//    Schema::create('courses', function (Blueprint $table) {
//        $table->id();
//        $table->unsignedInteger('category_id');
//        $table->string('name');
//        $table->timestamps();
//    });

    public function category()
    {
        return $this->belongsTo(Category::class,'category_id','id')
            ->with('parent');
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
//    Schema::create('categories', function (Blueprint $table) {
//        $table->id();
//        $table->unsignedInteger('parent_id');
//        $table->string('name');
//        $table->timestamps();
//    });

    protected $guarded = [];

    public function parent()
    {
        return $this->belongsTo(get_class($this))->with('parent');
    }

    public function child()
    {
        return $this->hasMany(get_class($this), 'parent_id');
    }

    public function children()
    {
        return $this->child()->with('children', 'parent');
    }
}

Route::get('demo', function () {
    \App\Models\Category::insert([
        [
            'parent_id' => 0,
            'name'      => '理学',
        ],
        [
            'parent_id' => 1,
            'name'      => '物理学',
        ],
        [
            'parent_id' => 2,
            'name'      => '天体物理',
        ],
        [
            'parent_id' => 3,
            'name'      => '量子力学',
        ],
    ]);

    \App\Models\Course::insert([
        [
            'category_id' => 4,
            'name'        => '暗物质',
        ],
        [
            'category_id' => 4,
            'name'        => '暗能量',
        ],
    ]);

    return \App\Models\Course::with('category')->first();
});
{
    "id": 1,
    "category_id": 4,
    "name": "暗物质",
    "created_at": null,
    "updated_at": null,
    "category": {
        "id": 4,
        "parent_id": 3,
        "name": "量子力学",
        "created_at": null,
        "updated_at": null,
        "parent": {
            "id": 3,
            "parent_id": 2,
            "name": "天体物理",
            "created_at": null,
            "updated_at": null,
            "parent": {
                "id": 2,
                "parent_id": 1,
                "name": "物理学",
                "created_at": null,
                "updated_at": null,
                "parent": {
                    "id": 1,
                    "parent_id": 0,
                    "name": "理学",
                    "created_at": null,
                    "updated_at": null,
                    "parent": null
                }
            }
        }
    }
}

是这样吗?

3年前 评论
Hi_Debug (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!