仅显示Laravel

时间:2016-06-07 09:56:05

标签: php mysql laravel-4

我试图仅显示所选类别的产品,但出现问题,我仍然无法理解。

到目前为止我所做的是在routes.php

中添加了路线
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

当我现在运行页面时,我得到了所有产品......无论我点击什么类别

1 个答案:

答案 0 :(得分:2)

首先在您的类别模型中,您必须与产品建立关系,因此请添加以下内容:

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