So filtern Sie Produkte nach Attributen (Farbe, Größe usw.) in Laravel
P粉821274260
P粉821274260 2023-08-28 00:17:09
0
2
535
<p>Ich bin neu bei Laravel und möchte bestimmte Produkte herausfiltern. </p> <p>Ich habe zwei Tabellen in meiner Datenbank, die erste ist die Tabelle <code>products</code> und die zweite ist die Tabelle <code>attributes</code>. </p> <p><strong>Produktliste</strong></p> <pre class="brush:php;toolbar:false;">Schema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->BigInteger('category_id')->unsigned()->nullable(); $table->string('name'); $table->string('code'); $table->integer('status')->default(1); $table->integer('featured')->default(1); $table->string('image'); $table->longText('short_description'); $table->longText('long_description'); $table->timestamps(); })</pre> <p><strong>Produktattributtabelle</strong></p> <pre class="brush:php;toolbar:false;">Schema::create('product_attributes', function (Blueprint $table) {. $table->bigIncrements('id'); $table->unsignedBigInteger('product_id'); $table->string('sku'); $table->string('size'); $table->string('color'); $table->string('price'); $table->string('stock'); $table->timestamps(); })</pre> <p><strong>Beziehungen</strong></p> <p>Weil ich mehrere Attribute für ein einzelnes Produkt habe</p> <pre class="brush:php;toolbar:false;">class Produkt erweitert Modell { benutze HasFactory; öffentliche Funktionsattribute() { return $this->hasmany('AppModelsProductAttributes', 'product_id'); } }</pre> <p><strong>Meine Blade-Dateien</strong></p> <pre class="brush:php;toolbar:false;"><form action="{{url('/product/filter')}}" @csrf <input type="hidden"value="{{$slug}}"name="slug"> <div class="custom-control custom-checkbox d-flex align-items-center justify-content-between mb-3"> "input name="color" onchange="javascript:this.form.submit();" type="radio" ;black"> <label class="custom-control-label" for="black">Black</label> </div> </form></pre> <p>Ich habe eine Funktion in meinem Controller</p> <pre class="brush:php;toolbar:false;">public function shop() { $filter_products = Product::with('attributes')->where(['category_id' => $category->id, 'color' => $request->color]); return view('frontend.shop', compact('filter_products')); }</pre> <p>Ich erhalte keine Ergebnisse, nachdem ich diese Funktion angewendet habe</p> <p>Bitte zeigen Sie mir auf der Frontend-Store-Seite, wie ich Produkte nach einer bestimmten Größe oder Farbe filtern kann. und welcher Code in die Store-Funktionalität einbezogen wird. </p> <p>Bitte antworten Sie mir, ich werde Ihnen vielmals danken</p>
P粉821274260
P粉821274260

Antworte allen(2)
P粉908138620
$brands         = Brand::orderBy('id','DESC')->get();
    $colors         = Color::orderBy('id','DESC')->get();
    $sizes          = Size::orderBy('id','DESC')->get();
    $weights        = Weight::orderBy('id','DESC')->get();
    $tags           = Tag::orderBy('id','DESC')->get();
    try{
        if (!empty($_GET['colors']) || !empty($_GET['brands']) || !empty($_GET['sizes']) || !empty($_GET['weights']) || !empty($_GET['tags'])) {
            $products = Product::where( function($query ){
                $query->when(!empty(request()->colors) ,function($subquery){
                    $subquery->whereHas('colors', function($subquery)  {
                        $subquery->whereIn('colors.id',request()->colors);
                    });
                })->when(!empty(request()->sizes) ,function($subquery){
                    $subquery->whereHas('sizes', function($subquery)  {
                        $subquery->whereIn('sizes.id',request()->sizes);
                    });
                })->when(!empty(request()->weights) ,function($subquery){
                    $subquery->whereHas('weights', function($subquery)  {
                        $subquery->whereIn('weights.id',request()->weights);
                    });
                })->when(!empty(request()->tags) ,function($subquery){
                    $subquery->whereHas('tags', function($subquery)  {
                        $subquery->whereIn('tags.id',request()->tags);
                    });
                })->when(!empty(request()->brands) ,function($subquery){
                    $subquery->whereHas('brand', function($subquery)  {
                        $subquery->whereIn('brand_id',request()->brands);
                    });
                })->when(!empty(request()->is_new) ,function($subquery){
                    $subquery->where('is_new',request()->is_new);
                })->when(!empty(request()->gender) ,function($subquery){
                    $subquery->where('gender', 'LIKE', "%" . request()->gender . "%");
                });
            })->paginate(10);
        
            
            return view('front.shop',compact('products','brands','colors','sizes','weights','tags'));
        } else {
            return  redirect()->route('products');
        }
        
    } catch (\Exception $e) {
        toastr()->error(trans('Some thing is wrong please try again'));
        return  redirect()->route('products');
    }
P粉033429162

您需要按关系进行过滤,请查看文档

https://laravel.com/docs/9 .x/eloquent-relationships#querying-relationship-existence

举例说明 使用WhereHas

$filter_products = Product::with('attributes')
   ->where(['category_id' => $category->id])
   ->whereHas('attributes',function($query) use($request){
      $query->where(['color' => $request->color]);
   });

如果 with 中没有应用任何地方,则将返回所有属性

您可以使用在 whereHas 中应用的相同过滤器来防止这种行为

$filter_products = Product::with(['attributes'=>function($query) use($request){
        $query->where(['color' => $request->color]);
    }])
    ->where(['category_id' => $category->id])
    ->whereHas('attributes',function($query) use($request){
        $query->where(['color' => $request->color]);
    });
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!