使用Laravel Eloquent需要根据category id获取所有商品

Using Laravel Eloquent need to get all products according to category id

我需要根据类别id 获取所有产品。 这是我的控制器。

UserProductsController

class UserProductsController extends Controller
{
    public function index()
    {
        $products = Product::get();
        return view ('products')->with(compact('products'));
      
    }
      
    public function product_categories()
    {
        $categories = Category::all();
        return view ('categories')->with(compact('categories'));
      
    }


    public function products(Category $category)
    {
        $category->load('products');

        return view('categorize')->withCategory($category);
    } 
  

}

这是我的 blade 文件。

    @foreach($category as $c) 
     <div class="mb-2" class="font-size-12 text-gray-5">{{ $c ['cat_name'] }}</a></div>
        <h5 class="mb-1 product-item__title" class="text-blue font-weight-bold">{{ $c ['prod_name'] }}</a></h5>
            <li class="line-clamp-1 mb-1 list-bullet">{{ $c ['prod_description'] }}</li>
            <div class="text-gray-20 mb-2 font-size-12">{{ $c ['prod_item_code'] }}</div>
            <div class="flex-center-between mb-1">
                <div class="prodcut-price">
                   <div class="text-gray-100">LKR {{ $c ['prod_price'] }}.00</div>
                </div>
            </div>
        </div>
@endforeach

这是我的路由文件。

Route::get('/categorize/{category_id}', 'UserProductsController@products')->name('categorize');

这是类别 table。

public function up()
    {
       Schema::create('categories', function (Blueprint $table)
        {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('parent_id')->nullable();
        $table->string('cat_name')->nullable();
        $table->string('cat_image_path')->nullable();
        $table->timestamps();
         });
    }

这是我的产品table。

public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('prod_name');
            $table->string('prod_brand')->nullable();
            $table->unsignedBigInteger('category_id');
            $table->string('prod_description')->nullable();
            $table->string('prod_item_code')->nullable();
            $table->string('prod_modal')->nullable();
            $table->string('prod_size')->nullable();
            $table->string('prod_weight')->nullable();
            $table->string('prod_height')->nullable();
            $table->string('prod_manufacturer')->nullable();
            $table->float('prod_price')->nullable();
            $table->float('prod_discount')->nullable();
            $table->float('prod_quantity')->nullable();
            $table->string('prod_image_path')->nullable();
            $table->timestamps();

            $table->foreign('category_id')
            ->references('id')
            ->on('categories')
            ->onDelete('cascade');
        });
    }

这是我的类别模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


class Category extends Model
{
    public function products()
    {
       return $this->hasMany(Product::class);
    }
}

这是我的产品模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Storage;

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

当我 select 特定类别时,我的 URL 将我引导至 category_id 的页面,但数据未通过。可能是什么问题呢?有人可以指导我吗?

您可以通过预先加载来做到这一点。 预加载 是一种概念,在该概念中,当检索项目时,您会同时获得所有需要的项目以及所有(或大部分)相关项目。这与延迟加载形成对比,后者一次只获取一项,然后仅在需要时检索相关项

类别模型:

public function products()
{
   return $this->hasMany(Product::class);
}

在你的控制器上:

public function products(Request $request, $category_id)
{
    $category= Category::with('products')->findOrFail($category_id);
    return view('categorize')->with(compact('category'));
}

据我了解,您在前端有一些 'category id'(可能 HTML),并且您想通过某些路线传递该 ID '/categorize/{category_id} ' 到您的控制器并获取与其关联的所有产品。所以你必须像下面这样重构你的控制器方法。

 public function products(int $category_id)
{
     $products = Product::where('category_id',$category_id)->get();
    return view ('categorize')->with(compact('products'));
} 

如果您有任何不同的需求,请随时提出并详细说明您的问题。我一定会帮你的。

正如你在路线中提到的 category_id 所以在控制器中你需要做

 public function products(Category $category_id) // parameter name should match with router param
    {
        $category_id->load('products');
        $category  = $categoryid;
        return view('categorize')->withCategory($category);
    } 

或者你可以这样做的正确方法

Route::get('/categorize/{category}', 'UserProductsController@products')->name('categorize');

category_idcategory 那么你的路由模型绑定就可以工作了

ref link https://laravel.com/docs/7.x/routing#route-model-binding

如果你想使用路由模型绑定,你必须像这样定义你的路由:

Route::get('/categorize/{category}', 'UserProductsController@products')->name('categorize');

所以在这种情况下 $category 实际上是一个模型,而不是一个集合。因此,您当前拥有的 foreach 没有意义。它应该是这样的:

@foreach($category->products as $product) 
    <div>{{ $product->prod_name }}</div>
    ...
@endforeach