【问题标题】:Laravel Eloquent how to get all products in a category with slugLaravel Eloquent 如何使用 slug 获取一个类别中的所有产品
【发布时间】:2016-12-28 07:17:13
【问题描述】:

我的 Productcategory.php 有

public function products()
{
    return $this->hasMany('App\Models\Product');
}

Product.php 有

public function productcategory()
{
    return $this->belongsTo('App\Models\Productcategory', 'category_id');
}

现在我的路线是

Route::get('gallery/{slug}', 'GalleryController@index');

当 URL 类似于 gallery/print-pattern-client-work 时,我怎样才能获得所有具有相同类别的产品?我有以下但category_id 是一个整数而不是一个蛞蝓。所以我不太确定该怎么做。

public function index()
{
    $categoryslug = Request::segment(2);
    $products = Productcategory::with('products')->where('category_id',$categoryslug)->get();
...
}

【问题讨论】:

  • print-pattern-client-work 是任何类别吗?

标签: laravel eloquent


【解决方案1】:

这假设您的 product_categories 表中有一个名为“slug”的列。而且你所描述的关系运作良好。

你可以在 Product.php 中创建一个访问器

public function scopeFindByCategorySlug($query, $categorySlug)
{
    return $query->whereHas('productcategory', function ($query) use ($categorySlug) {
        $query->where('slug', $categorySlug);
    });
}

然后在你的控制器中调用这个:

public function index(Request $request, $slug)
{
    $products = Product::findByCategorySlug($slug)->get();
}

编辑:

正如在 cmets 中提到的,实际上并不需要访问器。这基本上就是您所需要的(在控制器中):

public function index(Request $request, $slug)
{
    $products = Product::whereHas('productcategory', function ($query) use ($categorySlug) {
        $query->where('slug', $categorySlug);
    })->get();
}

【讨论】:

  • 他也可以直接在index方法中做whereHas,但你的答案确实是唯一正确的。
  • 谢谢,这行得通。 $products = Product::whereHas('productcategory', function ($query) use ($slug) { $query->where('slug', $slug); })->get();
【解决方案2】:

不要

$categoryslug = Request::segment(2);

使用$slug

public function index($slug)
{
    $products = Productcategory::with('products')->where('category_id',$slug)->get();
...
}

【讨论】:

    【解决方案3】:

    当你使用 Laravel 时,你应该像这样使用 Laravel 的Many to Many Relationships

    你的表结构是这样的:

    - products
        - id
        - name
        - ...
    
    - categories
        - id
        - name
        - slug
        - ...
    
    - category_product
        - id
        - category_id
        - product_id
        - ...
    

    你的模型应该是这样的:

    class Product extends Model {
    
        public function categories() {
            $this->belongsToMany(Category::class, 'category_product');
        }
    
    }
    
    class Category extends Model {
    
        public function products() {
            $this->belongsToMany(Product::class, 'category_product');
        }
    
    }
    

    您可以像这样获取特定$category_slug 的所有产品:

    $category = Category::where('slug', $category_slug)->first();
    if($category) {
        $products = $category->products;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多