我的專案中有 3 個表,它們是:
- 產品(可以有多個變體)
- 變體(屬于產品)
- product_attributes(這有product_id、attribute_id、value_id)
我想通過來自表單請求的值 ID 過濾產品的變體,例如 (1,2,6)
我試過這樣:
$poruduct_id = $request->product_id;
$value_ids = $request->value_ids;
$searched_variants = Variant::whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->where('product_id', $product_id)->get();
dd($searched_variants);
但問題是查詢回傳產品中的所有記錄。精確過濾產品變體具有的值的解決方案是什么?
謝謝你。
-更新-
我試過這樣但沒有任何改變
$searched_variants = Variant::select('product_id')->whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->groupBy('product_id')
->havingRaw('COUNT(*) = ?', [count((array) $value_ids)])
->get();
-**F?NALLY SOLUT?ON**-
I made it like this : I get the value code that is in for example Large the code is L
get all the codes to controller and executed this query ? hope this helps someone
1.$value_codes=$request->value_codes;
2.$value_codes_array=explode(',',$value_codes);
3.$product_id=$request->product_id;
4.$searchValues = preg_split('/,/', $value_codes_array, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = preg_split('/,/', $value_idss, -1, PREG_SPLIT_NO_EMPTY);
$variants= Variant::where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('sku', 'like', "%-{$value}")
->orWhere('sku', 'like', "%-{$value}-%")
->orWhere('sku', 'like', "{$value}-%");
}
})->where('product_id',$product_id)->get();
dd($variants);
uj5u.com熱心網友回復:
如果你有一個產品的 n 個變體,你的查詢應該是這樣的:
產品型號
公共函式變體:HasMany 關系
//用法 $produtc->variants->這里是查詢函式
uj5u.com熱心網友回復:
您需要以這種方式使用它,它應該可以作業:
$productId = $request->product_id;
$valueIds = $request->value_ids;
$searchedVariants = Variant::whereHas('product.attributeValues', function ($query) use ($valueIds) {
$query->distinct()->whereIn('value_id', $valueIds);
}, '=', count($valueIds))->where('product_id', $productId)->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/325116.html
下一篇:Git合并后會丟失一些檔案
