【问题标题】:Using Laravel Eloquent need to get all products according to category id使用 Laravel Eloquent 需要根据类别 id 获取所有产品
【发布时间】:2020-09-09 05:12:06
【问题描述】:

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

用户产品控制器

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);
    } 
  

}

这是我的刀片文件。

    @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');

这是类别表。

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();
         });
    }

这是我的产品表。

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');
    }
}

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

【问题讨论】:

    标签: php laravel e-commerce


    【解决方案1】:

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

    类别模型:

    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'));
    }
    

    【讨论】:

    • 我收到此错误:ErrorException 未定义变量:类别(查看:C:\xampp\htdocs\bizzcomputer\resources\views\categorize.blade.php)。它提到了这一行: foreach($category as $c) @sta
    【解决方案2】:

    我的理解是,您在前端有一些“类别 id”(可能是 HTML),并且您想通过某些路由“/categorize/{category_id}”将该 id 传递给您的控制器并获取所有与之关联的产品它。所以你必须重构你的控制器方法,如下所示。

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

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

    【讨论】:

      【解决方案3】:

      当你在你的路线中提到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 然后您的路由模型绑定将起作用

      参考链接https://laravel.com/docs/7.x/routing#route-model-binding

      【讨论】:

        【解决方案4】:

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

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-09
          相关资源
          最近更新 更多