【发布时间】:2019-11-22 08:52:13
【问题描述】:
【问题讨论】:
【问题讨论】:
只需使用 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")
【讨论】:
您可以使用此代码
$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);
结果
【讨论】:
products -> Products