我正在嘗試使用 laravel 中的 groupBy 方法獲取資料,但它正在回傳所有資料。我想要得到的是
讓有2張桌子
表 1:變體
id variant
1 color
2 size
表 2:product_variants
color variant_id
red 1
yellow 1
red 1
sm 2
xl 2
lg 2
現在我想獲取資料,所以它回傳如下:
variant_table: {
id:1,
variant: color,
variants: {
variant_id: 1,
color:red
},
{
variant_id: 1,
color:yellow
}
},
{
id:2,
variant: size,
variants: {
variant_id: 2,
color:sm
},
{
variant_id: 2,
color:lg
},
{
variant_id: 2,
color:xl
}
}
但是我得到了所有變體而不是按變體表ID分組的不同,我的代碼:
$productVariants = ProductVariant::with('productVariants')
->whereHas('productVariants',function ($q) {
$q->groupBy('variant_id');
})
->get();
uj5u.com熱心網友回復:
假設 product_variants 表的模型是 ProductVariant 假設變數表的模型是 Variant 假設模型 ProductVariant 中的關系函式名稱是 variant()
$product_variants = ProductVariant::with('variant')->groupBy('variant_id')->get();
$product_variants = ProductVariant::with('variant')->get()->groupBy('variant_id');
如果它比 config\database.php 不起作用,試試這個--> "mysql" array Set 'strict' => false
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506727.html