【发布时间】:2018-05-01 06:46:02
【问题描述】:
我的应用中有一个 3 表。products,category,attributes
product hasMany category 和 category hasMany 属性关系。
我想以 json 格式获取所有 products 和 Category 详细信息和 catgoey attributes 详细信息。我该怎么做?
目前我正在我的控制器中尝试使用此功能:
public function index()
{
$productDetails = Product::all();
if(!empty($productDetails)) {
foreach ($productDetails as $key => $value) {
//print_r($value->id."</br>");
}
}
}
我想要的输出:
{
"productInformation": {
"id": 1,
"name": "productone",
"status": "Active",
"CategoryDetails": [
{
"id": 1,
"product_id": 1,
"categoryTitle": "categoryone",
"attribute" : [
{
"id": 1,
"product_id": 1,
"category_id": 1,
"title": "attrib-title-one",
},
{
"id": 2,
"product_id": 1,
"category_id": 1,
"title": "attrib-title-two",
},
]
}
]
}
}
关系:
在categories 表上
$table->foreign('product_id')->references('id')->on('products');
在attributes 表上:
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('category_id')->references('id')->on('categories');
我该怎么做?
【问题讨论】:
标签: laravel laravel-5.5