【发布时间】:2016-05-08 07:41:08
【问题描述】:
如标题所述,问题是如何根据产品列出父类下的子类。正如我在本文末尾的示例代码中所示,列出父类别及其所有子类别没有问题。但我需要根据产品列出子类别。
这是我的类别的示例结构:
Electronic -Computer -Phone -Gadget Grocery -Food -Drinks
这是我的产品表迁移:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->decimal('price')->nullable();
$table->timestamps();
});
这是我的类别表迁移
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id')->nullable();
$table->string('name')->nullable();
$table->string('description')->nullable();
$table->timestamps();
});
这是 category_product,它充当 category 和 product 之间的 many to many 表:
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->index();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
我已经建立了所有的关系。这是我的模型:
这是我的类别模型:
class Category extends Model
{
protected $table = 'categories';
protected $fillable = [
'name',
];
public function products()
{
return $this->belongsToMany('App\Product');
}
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
}
这是我的产品型号:
class Product extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category');
}
}
这是我的 ProductController.php,我可以使用此代码显示所有父类别及其子类别:
public function show($id)
{
$product = Product::findOrFail($id);
$categories = Category::with('children')->get();
return view('products.show', compact('product','categories'));
}
所以我的 product.shows.blade 看起来像这样:
@foreach($categories as $item)
@if($item->children->count() > 0 )
<li>
{{ $item->name }}
<ul>
@foreach($item->children as $submenu)
<li>{{ $submenu->name }}</li>
@endforeach
</ul>
</li>
@endif
@endforeach
//输出:
Electronic
Computer
Phone
Gadget
Grocery
Food
Drinks
但是假设这个特定产品(称为产品 1)的父类别为 电子,子类别为 计算机 和 电话我已经将它们附加到数据库中。这是数据库中数据的概述:
如何显示产品 1 的类别及其父类别和子类别?我希望输出像
Product 1
Category:
Electronic
Computer
Phone
更新:
所以,我所做的另一件事是添加 $product->categories,但代码只会列出 Product1 拥有的父类别及其所有子类别。它不会过滤特定于 Product1 的子类别
@foreach($product->categories as $item)
@if($item->children->count() > 0 )
<li>
{{ $item->name }}
<ul>
@foreach($item->children as $submenu)
<li>{{ $submenu->name }}</li>
@endforeach
</ul>
</li>
@endif
@endforeach
所以,而不是像这样的输出(我想要的):
Category:
Electronic
Computer
Phone
它会这样列出(这不是我想要的):
Category:
Electronic
Computer
Phone
Gadget
【问题讨论】:
标签: laravel eloquent laravel-5.1 query-builder laravel-5.2