我将 Laravel 5.8 和Laravel-nestedset用于我的类别模型,并且我有一个产品模型。
我成功地创建了嵌套类别并正确显示它们,但是当我到达一个有产品的类别时,我想显示属于当前类别的产品——下面的代码显示产品,但不在他们所属的类别。这是我想象的非常标准的东西,但我似乎无法弄清楚。
分类.php
<?php
namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;
class Category extends Model
{
use \Spatie\Tags\HasTags;
use HasSlug;
use NodeTrait;
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug');
}
public function getRouteKeyName()
{
return 'slug';
}
}
产品.php
<?php
namespace App;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use \Spatie\Tags\HasTags;
use HasSlug;
protected $dates = [
'published_on',
];
public function getSlugOptions() : SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
public function getRouteKeyName()
{
return 'slug';
}
public function category()
{
return $this->belongsTo(Category::class);
}
}
类别控制器.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Product;
class CategoryController extends Controller
{
public function index()
{
$categories = Category::get()->toTree();;
return view('categories.index', compact('categories'));
}
public function show(Category $category)
{
$products = Product::with('category')->whereIn('category_id', $category)->get();
return view('categories.show', compact('category', 'products'));
}
UYOU