您需要在表格中获取每个产品的结果
$product->features = [
[
'id' => 1,
'name' => 'Weight'
'values' => [
['value' => 10],
['value' => 15]
]
],
...
];
目前,我能够使用此代码获得这样的结果。
$products = Product::whereIsActive(true)->with([
'brand',
'categories',
'values.feature'
])->get([
'id',
'name',
'brand_id'
])->map(function($p, $key) {
foreach ($p->values as $v) {
if (! array_key_exists($v->feature->id, $p->features)) {
$p->features[$v->feature->id]['data'] = $v->feature;
}
$p->features[$v->feature->id]['values'][] = $v;
}
return $p;
});
最初,采样后的结果是
{
features => [],
values => [
0 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
],
1 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
]
],
}
做完之后map()
{
features => [
1 => [
id => 1,
name => 'Weight',
values => [
0 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
],
1 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
]
]
],
values => [
0 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
],
1 => [
'value' => 5,
'feature' => [
'id' => '1'
'name' => 'Weight'
]
]
],
}
但是,问题在于,为此,您需要在Product模型中创建一个附加模型。公共属性features并将迭代的结果写入其中。是否有另一种更正确和更简单的解决方案来解决这个问题?
产品
+----+-----------+-----------+
| id | is_active | name |
+----+-----------+-----------+
| 1 | 1 | Flower red|
+----+-----------+-----------+
class Product extends Model
{
public $features = [];
public function values()
{
return $this->belongsToMany(
FeatureValue::class,
'feature_product',
'product_id',
'value_id',
'id'
)->withPivot('product_id','feature_id', 'value_id');
}
}
特征和特征值
+----+--------+ +----+------------+-------+
| id | name | | id | feature_id | value |
+----+--------+ +----+------------+-------+
| 1 | Weight | | 1 | 1 | 3 |
+----+--------+ | 2 | 1 | 5 |
+----+------------+-------+
class Feature extends Model
{
public function values()
{
return $this->hasMany(FeatureValue::class)->orderBy('id', 'desc');
}
}
class FeatureValue extends Model
{
public function feature()
{
return $this->belongsTo(Feature::class);
}
public function product()
{
return $this->belongsToMany(
Product::class,
'feature_product',
'product_id'
);
}
}
枢轴特征_产品
+------------+------------+----------+
| feature_id | product_id | value_id |
+------------+------------+----------+
| 1 | 1 | 1 |
| 1 | 1 | 2 |
+------------+------------+----------+
您可以在 Products 模型中描述您需要的属性。
并且这个方法会在 $product->features 被调用的时候执行