Tuesday, May 1, 2018

Laravel : Three table with relationship to get data - development

Laravel : Three table with relationship to get data

I have a 3 table in my app.products,category,attributes
product hasMany category and category hasMany attributes relationship.

I want to get all products with Category details and catgoey attributes detail in json format.How can i do this?

Currently i am trying with this function in my controller:

public function index()
{
    $productDetails = Product::all();
    if(!empty($productDetails)) {
        foreach ($productDetails as $key => $value) {
            //print_r($value->id."</br>");
        }
    }
}

Output which i want :

       {
       "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",
                        },
                    ]
                }
            ]
        }
    }

relationship :

On categories table

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

On attributes table :

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

How can i do this ?



from Laravel Questions and Answers https://laravelquestions.com/laravel/laravel-three-table-with-relationship-to-get-data/
via Lzo Media

No comments:

Post a Comment