我将 Laravel 5.8 和Laravel-nestedset用于我的类别模型,并且我有一个产品模型。我成功地创建了嵌套类别并正确显示它们,但是当我到达一个有产品的类别时,我想显示属于当前类别的产品——下面的代码显示产品,但不在他们所属的类别。这是我想象的非常标准的东西,但我似乎无法弄清楚。分类.php<?phpnamespace 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<?phpnamespace 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<?phpnamespace 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')); }
1 回答
UYOU
TA贡献1878条经验 获得超4个赞
products()在 Category 模型中定义关系
public function products()
{
return $this->hasMany(Product::class);
}
你从一个实例化的类别访问关系,如下所示:
@if (count($category['children']) > 0)
@foreach($category['children']->chunk(3) as $chunk)
<div class="row">
@foreach($chunk as $category)
// ...
@foreach($category->products as $product)
@endforeach
// ...
@endforeach
</div>
@endforeach
@endif
- 1 回答
- 0 关注
- 185 浏览
添加回答
举报
0/150
提交
取消