简体   繁体   English

使用 Laravel Eloquent 需要根据类别 id 获取所有产品

[英]Using Laravel Eloquent need to get all products according to category id

I need to get all products according to its category id.我需要根据其类别 ID 获取所有产品。 This is my controller.这是我的控制器。

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

}

This is my blade file.这是我的刀片文件。

    @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

This is my route file.这是我的路由文件。

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

This is the Categories 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();
         });
    }

This is my Products 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');
        });
    }

This is my category model.这是我的类别模型。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;


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

This is my product model.这是我的产品型号。

<?php

namespace App;

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

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

When I select the particular category my URL is directing me to that category_id's page, but the data doesn't pass.当我选择特定类别时,我的 URL 将我定向到该 category_id 的页面,但数据没有通过。 What could be the problem?可能是什么问题呢? Anyone please direct me?有人请指导我吗?

You can do that with eager loading.你可以通过预先加载来做到这一点。 Eager loading is a concept in which when retrieving items, you get all the needed items together with all (or most) related items at the same time. Eager loading是一个概念,其中在检索项目时,您可以同时获得所有需要的项目以及所有(或大多数)相关项目。 This is in contrast to lazy loading where you only get one item at one go and then retrieve related items only when needed这与延迟加载相反,延迟加载一次只能获取一项,然后仅在需要时检索相关项

Category model :类别型号:

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

On your controller :在您的控制器上:

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

what I understand, is that you have some 'category id' in frontend( maybe HTML) and you want to pass that id via some route '/categorize/{category_id}' to your controller and get the all products associate with it.我的理解是,您在前端(可能是 HTML)中有一些“类别 id”,并且您想通过某个路由“/categorize/{category_id}”将该 id 传递给您的控制器并获取与其关联的所有产品。 so you have to refactor your controller method like below.所以你必须像下面这样重构你的控制器方法。

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

If you have any different needs then feel free to ask and elaborate more about your problem.如果您有任何不同的需求,请随时询问并详细说明您的问题。 I will definitely help you.我一定会帮助你的。

as u mention category_id in your route so in controller u need to do正如你在路线中提到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);
    } 

Or correct way u can do this或者你可以这样做的正确方法

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

category_id to category then your route model binding will work category_idcategory那么你的路由模型绑定将起作用

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

If you want to use route model binding, you'll have to define your route like so:如果要使用路由模型绑定,则必须像这样定义路由:

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

So in this case $category is actually a model, not a collection.所以在这种情况下$category实际上是一个模型,而不是一个集合。 So the foreach you currently have doesn't make sense.所以你目前拥有的foreach没有意义。 It should be something like:它应该是这样的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM