如何在 Laravel 中透過屬性(顏色、尺寸等)過濾產品
P粉821274260
2023-08-28 00:17:09
<p>我是 Laravel 新手,想要過濾掉特定產品。 </p>
<p>我的資料庫中有兩個表,第一個是表<code>products</code>,第二個是表<code>attributes</code>。 </p>
<p><strong>產品表</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>產品屬性表</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>關係</strong></p>
<p>因為我有單一產品的多個屬性</p>
<pre class="brush:php;toolbar:false;">class Product extends Model
{
use HasFactory;
public function attributes()
{
return $this->hasmany('App\Models\ProductAttributes', 'product_id');
}
}</pre>
<p><strong>我的刀片檔案</strong></p>
<pre class="brush:php;toolbar:false;"><form action="{{url('/product/filter')}}" method="post">
@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" class="custom-control-input" id=" class="custom-control-input" id=" ;black"> <label class="custom-control-label" for="black">Black</label>
</div>
</form></pre>
<p>我的控制器中有一個函數</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>應用此函數後我沒有得到任何結果</p>
<p>請指導我如何根據特定尺寸或顏色在前端商店頁面過濾產品。
以及商店功能中將包含哪些代碼。 </p>
<p>請回覆我,我會非常感謝你</p>
您需要按關係過濾,請查看文件
https://laravel.com/docs/9 .x/eloquent-relationships#querying-relationship-existence
#舉例說明 使用WhereHas
如果 with 中沒有應用任何地方,則會傳回所有屬性
您可以使用 whereHas 中套用的相同篩選器來防止這種行為