laravel 中的分层类别 url

问题描述 投票:0回答:1

我正在使用 Laravel 10。

我创建了以下表格来存储和使用类别(基于 WordPress 数据库架构)

术语表架构:

public function up() {
  Schema::create('terms', function (Blueprint $table) {
    $table->bigIncrements('term_id');
    $table->string('name', 200)->nullable();
    $table->string('slug', 300)->unique()->index();
    $table->timestamps();
  });
}

term_taxonomy 表架构:

public function up() {
  Schema::create('term_taxonomy', function (Blueprint $table) {
    $table->bigIncrements('term_taxonomy_id');
    $table->bigInteger('term_id')->unsigned();
    $table->string('taxonomy');
    $table->string('icon')->nullable();
    $table->text('description')->nullable();
    $table->bigInteger('parent')->unsigned()->default(0); 
    $table->bigInteger('count')->default(0);
    $table->timestamps();
    $table->foreign('term_id')->references('term_id')->on('terms')->onDelete('cascade');
  });
}

问题:

在 Laravel 中,如何创建分层类别 URL,例如:

domain.com/top-travel/ //parent 1
domain.com/top-travel/sea //child of parent 1

这样子类别(sea)与父类别(top-travel)将具有 URL“domain.com/top-travel/sea”,而不仅仅是“domain.com/sea”

请尽可能详细地向我展示如何执行此操作。我是 Laravel 的新手,尝试了几种方法,但似乎都无法让它们正常工作。我正在尝试完全理解 Laravel 的这个具体问题。

-- 更新一个 --

我写的代码有点像这样: 在 CategoryController.php 中

public function show($slug)
{
    // Find the post based on the slug
    $category = Term::whereSlug($slug)->firstOrFail();
    
    // Get the list of parent categories
    $parents = [];
    $parent = $category->taxonomy;
    
    // Traverse through parent categories until reaching parent = 0
    while ($parent && is_object($parent) && $parent->parent) {
        $parents[] = $parent->slug;
        $parent = $parent->parent;
    }
    
    // If there are parent categories, add them to the URL
    $url = empty($parents) ? '' : implode('/', array_reverse($parents)) . '/';
    
    // Check if $parent is an object before accessing the 'slug' property
    if (is_object($parent)) {
        $url .= $parent->slug . '/';
    }
    
    // Add the current category slug to the URL
    $url .= $slug;
    
    // If there are no parent categories, use the basic path
    if (empty($parents)) {
        $url = 'cat/' . $slug;
    }
    
    // Get the icon and description values from the term_taxonomy table
    $icon = $category->taxonomy->icon;
    $description = $category->taxonomy->description;
    
    // Display the post
    return view('categories.show', compact('category', 'icon', 'description', 'url'));
}

在此代码中,我尝试通过遍历父类别并将其 slugs 添加到 URL 路径来构造 URL。然而,挑战仍然在于管理层次结构和创建正确的 URL 结构。如果您对如何改进这一点有任何建议或见解,我将不胜感激!”

laravel hierarchical
1个回答
0
投票

在此文档的基础上,您需要在路由中定义正则表达式,如下所示:

Route::get('product/{category}', [CategoryController::class, 'show'])
    ->where('category', '([a-zA-Z0-9\-\/]+)');

如果您随后调用“domain.com/product/test1/test2”,控制器中的类别参数将如下所示:

'test/test2'

您所要做的就是解析该字符串以找到您的类别。

注意: 使用此方法后,

product
之后的所有路线都将成为一个类别,并会执行
show
中的
CategoryController
动作!

© www.soinside.com 2019 - 2024. All rights reserved.