答案 0 :(得分:1)
只需使用SQL左联接
select p.id, color.value as 'color',weight.value as 'weight' from Products p
left join Values color on (p.id = color.product_id)
inner join Fields fcolor on (color.field_id = fcolor.id and fcolor.name = "color")
left join Values weight on (p.id = color.product_id)
inner join Fields fweight on (weight.field_id = fweight.id and fweight.name = "weight")
答案 1 :(得分:0)
您可以使用此代码
$fields = DB::table('fields')->pluck('name', 'id')->all();
$query = DB::table('products')->selectRaw('id as product_id, name as product_name');
foreach ($fields as $id => $value) {
$raw = sprintf(
'(select `value` from `values` where `values`.product_id = products.id and `values`.field_id = %s LIMIT 1) as %s',
$id,
$value
);
$query->selectRaw($raw);
}
$result = $query->get()->toArray();
dd($result);
这样的结果
如果提交的产品可以具有多个属性,则可以将此属性与GROUP_CONCAT
一起使用
$fields = DB::table('fields')->pluck('name', 'id')->all();
$query = DB::table('products')->selectRaw('id as product_id, name as product_name');
foreach ($fields as $id => $value) {
$raw = sprintf(
'(select GROUP_CONCAT(`value`) from `values` where `values`.product_id = products.id and `values`.field_id = %s ) as %s',
$id,
$value
);
$query->selectRaw($raw);
}
$result = $query->get()->toArray();
dd($result);
结果类似