Cara menapis produk mengikut atribut (warna, saiz, dll.) dalam Laravel
P粉821274260
P粉821274260 2023-08-28 00:17:09
0
2
608
<p>Saya baru menggunakan Laravel dan ingin menapis produk tertentu. </p> <p>Saya mempunyai dua jadual dalam pangkalan data saya, yang pertama ialah jadual <kod>produk</kod> dan yang kedua ialah jadual <kod>atribut</kod>. </p> <p><strong>Senarai Produk</strong></p> <pre class="brush:php;toolbar:false;">Skema::create('products', function (Blueprint $table) { $table->bigIncrements('id'); $table->BigInteger('category_id')->unsigned()->nullable(); $table->string('nama'); $table->string('kod'); $table->integer('status')->default(1); $table->integer('ditampilkan')->default(1); $table->string('imej'); $table->longText('short_description'); $table->longText('long_description'); $table->cap masa(); })</pre> <p><strong>Jadual atribut produk</strong></p> <pre class="brush:php;toolbar:false;">Skema::create('product_attributes', function (Blueprint $table) {. $table->bigIncrements('id'); $table->unsignedBigInteger('product_id'); $table->string('sku'); $table->string('saiz'); $table->string('color'); $table->string('harga'); $table->string('stok'); $table->cap masa(); })</pre> <p><strong>Hubungan</strong></p> <p>Kerana saya mempunyai berbilang atribut untuk satu produk</p> <pre class="brush:php;toolbar:false;">class Produk memanjangkan Model { gunakan HasFactory; atribut fungsi awam() { return $this->hasmany('AppModelsProductAttributes', 'product_id'); } }</pre> <p><strong>Fail Blade Saya</strong></p> <pre class="brush:php;toolbar:false;"><form action="{{url('/product/filter')}}" @csrf <jenis input="hidden"value="{{$slug}}"name="slug"> <div class="kotak semak tersuai-kawalan tersuai d-flex align-item-center justify-content-antara mb-3"> <nama input="warna"onchange="javascript:this.form.submit();"jenis="radio"id-kawalan" ;hitam"> <kelas label="label-kawalan tersuai" untuk="hitam">Hitam</label> </div> </form></pre> <p>Saya mempunyai fungsi dalam pengawal saya</p> <pre class="brush:php;toolbar:false;">kedai fungsi awam() { $filter_products = Produk::with('attributes')->where(['category_id' => $category->id, 'color' => $request->color]); return view('frontend.shop', compact('filter_products')); }</pre> <p>Saya tidak mendapat sebarang hasil selepas menggunakan fungsi ini</p> <p>Sila bimbing saya cara menapis produk berdasarkan saiz atau warna tertentu pada halaman kedai hadapan. dan kod apa yang akan disertakan dalam fungsi kedai. </p> <p>Sila balas kepada saya, saya akan berterima kasih banyak</p>
P粉821274260
P粉821274260

membalas semua(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

Anda perlu menapis mengikut perhubungan, sila semak dokumentasi

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

Contoh Gunakan WhereHas

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

Jika tidak digunakan di mana-mana, semua harta akan dikembalikan

Anda boleh menghalang tingkah laku ini menggunakan penapis yang sama digunakan di 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]);
    });
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan