簡體   English   中英

僅顯示Laravel中選定類別的產品

[英]Showing products only from selected category in Laravel

我試圖僅顯示所選類別的產品,但是出了點問題,我仍然不明白是什么。

到目前為止,我所做的是在routes.php添加了route

Route::get('/admin/category/single/{categoryId}', ['uses' => 'AdminController@categoriesCheck']);

然后在AdminController中我添加了

public function categoriesCheck() {
    $products = Product::paginate(15);
    $categories = Categories::all();
    return View::make('site.admin.single_category', [
        'categories' => $categories,
        'product' => $products
    ]);
}

所以有2個問題,如果我單擊category_id = 1,如何進行查詢以僅加載category_id = 1(我在產品表中的列中保存了每種產品的category_id)的產品,以及如何制作視圖頁面?

目前我有虛擬的single_category.blade.php

@extends('layouts.master')
@section('title', 'Categories')

@section('content')

<div class="col-xs-12">
    <h3>Products List</h3>
    <hr />

    <div class="row">
    @foreach($products as $i => $product)
        <div class="col-md-4">
            <div class="panel panel-default text-center">
                <div class="panel-heading">{{{ $product['title'] }}}</div>
                <div class="panel-body min-h-230">
                    @if($product['image'])
                        <img class="max-150" src="{{ $product['image'] }}" alt="{{{ $product['title'] }}}" />
                        <br /><br />
                    @endif
                    {{ str_limit($product->description_small, 100) }}
                    @if (strlen($product->description_small) > 100)
                       <br/><br /> <a href="{{ URL::to('product/single/' . $product->product_id) }} " class="btn btn-info btn-block view-more">View More</a>
                    @endif
                </div>
            </div>
        </div>
    @if(($i+1) % 3 == 0)
    </div><div class="row">
    @endif
    @endforeach
    </div>

    <hr />
    {{ $products->links() }}
</div>
@endsection

當我現在運行頁面時,我得到了所有產品……無論我單擊哪個類別

首先,必須在類別模型中與產品建立關系,因此添加以下內容:

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

然后,在您的控制器中,您必須接受路徑中的類別ID並由此查詢類別:

public function categoriesCheck( $categoryId ) 
{
    $category = Categories::with('products')->findOrFail( $categoryId );
    return View::make('site.admin.single_category', [
        'category' => $category
    ]);
}

最后,在您的視圖中檢查類別是否包含產品,以及是否有循環產品:

@if($category->products->count())
    @foreach($category->products as  $product)
        //DIsplay product data
    @endforeach
@endif

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM