简体   繁体   English

如何通过category_id列出子类别的名称?

[英]How to list name of subcategory by category_id?

I am trying to list subcategory name by category_id where category_id should be grouped and show all subcategory name of that grouped id. 我试图按category_id列出子类别名称,其中category_id应该分组,并显示该分组ID的所有子类别名称。 Please see the attached figure shown in below: 请看下面的附图:

此图片用于数据库

这是我从查询中得到的

In my web page category name shown repeatedly but I want category should be display one and subcategory name should be display. 在我的网页中,类别名称反复显示,但我希望类别应显示一个,而子类别名称应显示。 For example: 例如:

category name   || subcategory name||
Data Management || pa , roji       ||
Executive       || lov, true       ||

My simple using relationship query is: 我简单的使用关系查询是:

TeamSubCategory::with('category')->orderBy('weight')->get();

You could do something like this (semi-pseudo code since you didn't post any of your models or your view): 您可以执行以下操作(半伪代码,因为您没有发布任何模型或视图):

Controller: 控制器:

$categories = Category::with('teamsubcategory')->get();

View: 视图:

<table>
    @foreach ($categories as $category)
    <tr>
        <td>{{ $category->name }}</td>
        {{-- implode the teamsubcategories and join with a comma and space on the name value --}}
        <td>{{ $category->teamsubcategory->implode('name', ', ') }}</td>
    </tr>
    @endforeach
</table>

Try group by category_I'd. 尝试按类别分组。 And select group_concat(distinct name) as subcategory_name 然后选择group_concat(不同名称)作为subcategory_name

using group_concat : 使用group_concat

TeamSubCategory::with
->select('*', DB::raw('GROUP_CONCAT(name SEPARATOR ', ') as `name_concatenated`'))
->('category')->groupBy('category_id')->orderBy('weight')->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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