我有产品表:
id | name
-----------
1 | orange
2 | ampalaya
3 | mango
4 | pork
和类别表:
id | parent_id | name
----------------------
1 | 0 | fruits
2 | 0 | vegetables
3 | 1 | yellow fruits
4 | 3 | small fruits
5 | 2 | green vegies
6 | 0 | meat
7 | 0 | shape
8 | 7 | circle
9 | 7 | oblong
我有product_categories表:
product_id | category _id
--------------------------
1 | 1
1 | 4
3 | 1
3 | 3
3 | 4
2 | 2
2 | 5
4 | 6
1 | 7
1 | 8
3 | 7
3 | 9
我的问题是如何显示每种产品的类别?我想要这个输出:
product name | categories
---------------------------------------------------------------------
mango | fruits > yellow fruits > small fruits , shape > oblong
orange | fruits > small fruits , shape > circle
ampalaya | vegetables > green vegies
pork | meat
我在我的模型上试过这个功能:
public static function listCategories($product_id)
{
$product_cats = DB::table('product_categories as pc')
->join('categories as c','c.id','=','pc.category_id')
->where('pc.product_id',$product_id)
->select('c.id','c.parent_id','c.name','pc.category_id')
->get();
$categories = DB::table('categories')->get();
$category = array(
'categories' => array(),
'parent_cats' => array()
);
foreach($categories as $cat) {
$category['categories'][$cat->id] = $cat;
$category['parent_cats'][$cat->parent_id][] = $cat->id;
}
return Category::list_categories(0,$category,$product_cats);
}
public static function list_categories($parent, $category, $product_cats)
{
$html = "";
$ctr = count($product_cats) - 1;
if (isset($category['parent_cats'][$parent])) {
foreach ($category['parent_cats'][$parent] as $cat_id) {
if (!isset($category['parent_cats'][$cat_id])) {
foreach($product_cats as $key1 => $cats) {
if($cat_id == $cats->category_id) {
if($key1 == $ctr){
$html .= $category['categories'][$cat_id]->name;
} else {
$html .= $category['categories'][$cat_id]->name.', ';
}
}
$ctr--;
}
}
if (isset($category['parent_cats'][$cat_id])) {
foreach($product_cats as $key => $cats) {
foreach ($category['parent_cats'][$cat_id] as $cat_ids) {
if($cat_ids == $cats->parent_id) {
$html .= $category['categories'][$cat_ids]->name.' >> ';
}
}
if($cat_id == $cats->category_id) {
if($key == $ctr) {
$html .= $category['categories'][$cat_id]->name;
} else {
$html .= $category['categories'][$cat_id]->name.', ';
}
}
}
$ctr--;
$html .= Category::list_categories($cat_id, $category, $product_cats);
}
}
}
return $html;
}
在我的显示/查看页面上:
@foreach($products as $prod)
<tr>
<td> {!! $prod->name !!}</td>
<td> {!! Category::listCategories($prod->id) !!}</td>
</tr>
@endforeach
在我的控制器上:
$data['products'] = DB::table('products')->get();