【问题标题】:Products related to category与类别相关的产品
【发布时间】:2017-07-10 05:52:14
【问题描述】:

我在按与类别相关的价格订购产品时遇到问题。当我单击“按价格排序”时,它会显示按价格排序的所有类别的所有产品。我只需要展示与 url 中的类别相关的产品,按价格排序。
这是控制器:

class SortController extends MainController{

    public function sortBy($category_url, Request $request)
    {
        $sort = $request->get('sort', 'asc');
        $products = Product::orderBy('price', $sort, $category_url)->get();
        return view('content.sort')->with('products', $products);
    }
}

这是视图:

extends('master')
@section ('content')

<form id="order-product-form" method="get" action=">>
    {{url('shop/{category_url}/sort=ASC')}}"enctype="multipart/form-data">
@if ($products) 
    @foreach($products as $product)
        {{ $product['title']}}

【问题讨论】:

  • $category_url 的值是多少。是类别 ID 吗?
  • 值为 category_url
  • 你说:与url中的category相关的产品。这个类别在哪里?
  • 我不明白,告诉我你想看什么
  • 检查我的答案。

标签: php laravel laravel-5


【解决方案1】:

要根据相关模型过滤模型,请使用 whereHas()

$products = Product::whereHas('category', function ($query) {

    return $query->where('id', '=', $category_id); // You filter here by the required category
});

$products->orderBy('price', $sort, $category_url)->get();

【讨论】:

  • 我明白了,如何将它结合到我的函数中?
  • 你能告诉我你返回所有产品视图的控制器吗?
  • 这是控制器:class ShopController extends MainController { public function categories(){ self::$data['categories']=Categorie::all()->toArray(); self::$data['title']=self::$data['title'].'|店铺分类';返回视图('content.categories', self::$data); } 公共函数 products($category_url){ Product::getProducts($category_url, self:: $data);返回视图('content.products',self::$data); }
  • 模型:class Product extends Model { static public function getProducts($category_url, &$data){ $data['products']=$data['category']=[]; if ($category=Category::where('url','=', $category_url)->first()){ $category= $category->toArray(); $data['category']=$category; $data['title']=$data['title']. ' | ' . $category['title']; if ($products=Categorie::find($category['id'])->products){ $data['products']= $products->toArray(); }}}
【解决方案2】:

你需要 $category->products->title。

模型类别和产品之间有关系吗?

【讨论】:

  • 是的,他们之间有关系
猜你喜欢
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
相关资源
最近更新 更多