douxian3828 2018-04-17 07:03
浏览 10
已采纳

Laravel 5.6嵌套类别

I am using Laravel 5.6. I am stuck with the following. The structure of my category model is below.

id  | name              | cat_parent_id | slug
--- | ------------------| ------------- | ------------- 
1   | Parent - 1        | NULL          | parent-1 
2   | Parent - 2        | NULL          | parent-2 
3   | Child-1- P - 1    | 1             | ch-1-p-1 
4   | Child-1- P - 2    | 2             | ch-1-p-2 
5   | sCh-1-Ch-1-P- 2   | 4             | sch-1-ch-1-p-2 

To obtain children relationship I used the following method on the kblinked\Category model.

public function children()
{
  return $this->hasMany('kblinked\Category', 'cat_parent_id', 'id');
}

In my controller,

public function category(Category $category)
{
    $categories = $category->first()->children;

    return view('product.list', compact('categories'));
}

Here is my route

Route::get('/{category?}','ProductController@category');

I am able to fetch the first children using the following code. It shows the following, when I visit the url, http://trump.localhost/parent-2

Child-1- P - 2

However, it doesn't show anything when I visit http://trump.localhost/parent-2/ch-1-p-2

It should show following, but I don't see it.

sCh-1-Ch-1-P- 2

  • 写回答

2条回答 默认 最新

  • douyi6168 2018-04-21 00:02
    关注

    You have to adjust your route:

    Route::get('{category1}/{category2?}/{category3?}/{category4?}',
        'ProductController@category');
    

    And your controller:

    public function category(Category $category1, Category $category2 = null,
            Category $category3 = null, Category $category4 = null) {
        $category = collect(func_get_args())->filter()->last();
    
        $categories = $category->children;
    
        return view('product.list', compact('categories'));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么