繁体   English   中英

如何在 Laravel 或 PHP 中按类别过滤产品

[英]How To Filter Product By Category in Laravel or PHP

im trying to filter products by categories for example look at this url http://127.0.0.1:8000/index?category=php,html,js the result it must the products that have php and html languages. 这些是我的桌子

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('title',100);
    $table->text('description');
    $table->text('cover');
    $table->text('file');
    $table->integer('user_id');
    $table->integer('price');
    $table->timestamps();
});
Schema::create('languages', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->timestamps();
});
Schema::create('product_language', function (Blueprint $table) {
    $table->integer('product_id');
    $table->integer('technology_id');
});

产品模块

语言模块

PrTe 模块

索引控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Product;
use App\Language;
use App\PrTe; //this is the pr_tes table module, which have (product and languages) Foreign Keys

class HomeController extends Controller
{
    public function index()
    {
        $Products = new PrTe;
        $Queries = [];
        $Columns = [
            'languages.title'            => 'category',
        ];
        $CategoryParameters = array_filter(explode(',',request('category')),function($value){
            return !is_null($value) && $value !== '';
        });
        $Products = $Products::join('products', 'pr_tes.product_id', '=', 'products.id')
                             ->join('languages', 'pr_tes.language_id', '=', 'languages.id');
                             
        foreach ($Columns as $Field => $Column) 
        {
            if(request()->has($Column) && request($Column) != null)
            {
                $Products = $Products->where($Field,request($Column));
                $Queries[$Column] = request($Column); 
            }
        }
        $Products = $Products->groupBy('products.id');
        $Products = $Products->paginate(5)->appends($Queries);
        return view('index',compact('Products'));
    }
}

*这张桌子设计好不好

首先,关系language应该是languages ,因为它是一个 hasMany。

这样做的最Laravel方法是使用whereHas() 与此类似的东西,而不是您在自己的解决方案中尝试的所有箍。 仅使用 when 查询类别是否存在。

$CategoryParameters = array_filter(explode(',', request('category')), function($value) {
    return !is_null($value) && $value !== '';
});

$products = Product::whereHas('languages', function ($query) use ($CategoryParameters) {
    $query->when(count($CategoryParameters), function ($query) use ($CategoryParameters) {
        $query->whereIn('title', $CategoryParameters);
    });
})->get();

缺点是whereHas()与 join 解决方案相比产生的 SQL 语句的存在速度不那么快。 由于语言是编程语言,我不相信这个查询很快就会出现性能问题。 虽然代码更简单。

暂无
暂无

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

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