Laravel : 三个table有关系获取数据

Laravel : Three table with relationship to get data

我的应用程序中有一个 3 table。products,category,attributes product hasMany category 和 category hasMany 属性关系。

我想获取所有 productsCategory 详细信息和 catgoey attributes 详细信息 json format.How 我可以这样做吗?

目前我正在尝试在我的控制器中使用这个功能:

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

$table->foreign('product_id')->references('id')->on('products');

attributes table :

 $table->foreign('product_id')->references('id')->on('products');
 $table->foreign('category_id')->references('id')->on('categories');

我该怎么做?

您可以在模型中为不同的类别和属性定义关系,需要在产品模型中为类别(命名类别)定义一个 hasMany 关系,然后在类别(命名属性)模型中为属性定义另一个 hasMany 关系。之后你可以按照这个过程来准备你的数据数组

$productDetails = Product::all();
    if(!empty($productDetails)) {
        foreach ($productDetails as $key => $value) {  
            $productDetails[$key]['categorieDetails'] = $productDetails[$key]->categories;
         foreach ($productDetails[$key]['categorieDetails'] as $key2 => $value2) {  
            $productDetails[$key]['categorieDetails'][$key2]['
             attribute'] = $productDetails[$key]->categorieDetails[$key2]->attributes;

         }
        }

    }

然后您可以使用 json_encode 来生成您的 json 数据

您的产品型号

public function categories(){
return $this->hasMany('App\Category','product_id');
}

类别模型

public function attributes(){
return $this->hasMany('App\Attribute','cat_id');
}

在您的控制器中

public function index()
{
    $productDetails = Product::with('catgories.attributes')->get();
    if(!empty($productDetails)) {
        $jsonData = json_encode($productDetails->toArray());
    }
}

在你的控制器中

public function index()
{
    $productDetails = Product::with('catgories.attributes')->get();
    return response()->json($productDetails);
}