我正在尝试在网站标题中获取所有主要类别,但仅显示一个类别,有人可以为此提供解决方案吗?
这是ProductsController:
ProductsController.php
public function products($url = null)
{
$categories = Category::with('products')->where(['parent_id'=>0])->get();
$categoryDetails = Category::where(['url' => $url])->first();
if($categoryDetails->parent_id==0)
{
//if url is main category url
$subCategories = Category::where(['parent_id'=>$categoryDetails])->get();
$cat_ids = "";
foreach ($subCategories as $subCat) {
$cat_ids .= $subCat->id.",";
}
$productsAll = Product::whereIn('category_id',array($cat_ids))->get();
}
else
{
//if url is sub category url
$productsAll = Product::where(['category_id' => $categoryDetails->id])
->get();
}
return view('products.listing')
->with(compact('categories','categoryDetails','productsAll'));
}
在listing.blade.php
上,我将其与以下类别相关联:
{{ $categoryDetails->name }}
控制器代码:
Controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use App\Category;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public static function mainCategories(){
$mainCategories = Category::where(['parent_id' => 0])->get();
$mainCategories = json_decode(json_encode($mainCategories));
/*echo "<pre>"; print_r($mainCategories); die;*/
return $mainCategories;
}
}
我在标题视图中编写的代码:
header.blade.php
<?php use App\Http\Controllers\Controller;
$mainCategories = Controller::mainCategories();
?>
<!--some html-->
@foreach($mainCategories as $cat)
<div class="dropdown-content">
<a href="{{ asset('products/'.$cat->url) }}" style="margin-bottom: -10px;">{{ $cat->name }}</a>
</div>
@endforeach
答案 0 :(得分:0)
尝试更改
<?php use App\Http\Controllers\Controller;
$mainCategories = Controller::mainCategories();
?>
到
<?php
use App\Controller;
$mainCategories = Controller::mainCategories();
?>
或更直接地:
<?php
$mainCategories = App\Controller::mainCategories();
?>
在header.blade.php
答案 1 :(得分:0)
您可以为此使用查看数据(https://laravel.com/docs/master/views#passing-data-to-views):
在您的select P.test_result_calc_category, a.NumberofPatients from (select distinct test_result_calc_category FROM a1c) P
left join
(select test_result_calc_category, count (distinct patient_id) as NumberofPatients from a1c group by test_result_calc_category) a
ON P.test_result_calc_category = a.test_result_calc_category
文件中:
App/Providers/AppServiceProvider.php
只需使用:
public function boot()
{
View::share('mainCategories', Category::where(['parent_id' => 0])->get());
}
在您的模板文件中。