猿问

Laravel 5.8 - 使用 Laravel-nestedset 查询属于当前类别的产品

我将 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'));

    }


哔哔one
浏览 186回答 1
1回答

UYOU

products()在 Category 模型中定义关系public function products(){&nbsp; &nbsp; return $this->hasMany(Product::class);}你从一个实例化的类别访问关系,如下所示:@if (count($category['children']) > 0)&nbsp; &nbsp; @foreach($category['children']->chunk(3) as $chunk)&nbsp; &nbsp; &nbsp; &nbsp; <div class="row">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @foreach($chunk as $category)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @foreach($category->products as $product)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // ...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; @endforeach@endif
随时随地看视频慕课网APP
我要回答