所以有这个表:
产品
- name
- description
.etc
规范
name
product_specification 数据透视表,用于多对多关系
product_id
specification_id
value
产品型号
public function specs()
{
return $this->belongsToMany(Specification::class)->withPivot('value');
}
规格模型
public function parent()
{
return $this->belongsTo(Specification::class);
}
public function children()
{
return $this->hasMany(Specification::class, 'parent_id', 'id');
}
因此,产品附带具有父母的规格,我需要与父母取得联系。 有了资源,我可以拥有这个:
{
"data": [
{
"id": 1,
"name": "Apple iPhone 11 Pro 64GB Space Gray",
"slug": "apple-iphone-11-pro-64gb-space-gray",
"price": "99,999",
"description": "description",
"specs": [
{
"name": "Device type:",
"value": "Smartphone"
},
{
"name": "2G standarts:",
"value": "GSM 1800 / GSM 1900 / GSM 850 / GSM 900"
},
]
}
]
}
但是我希望这样:
{
"data": [
{
"id": 1,
"name": "Apple iPhone 11 Pro 64GB Space Gray",
"slug": "apple-iphone-11-pro-64gb-space-gray",
"price": "99,999",
"description": "description",
"specs": [
{
"name": "Characteristics",
"children": [
{
"id": 2,
"name": "Device type:",
"value": "Smartphone"
},
{
"id": 2,
"name": "Device type:",
"value": "Smartphone"
},
]
},
{
"name": "Processor",
"children": [
{
"id": 2,
"name": "Processor type:",
"value": "Apple A13 Bionic"
},
{
"id": 2,
"name": "other spec:",
"value": "other spec child value"
},
]
}
]
}
]
}