Tuesday, March 26, 2024

How to Create JSON Structure in SQL Queries

In modern web development, handling relational data efficiently is crucial. Sometimes, we need to structure our data in JSON format within SQL queries, especially when dealing with 1:1 and 1:many relationships. Let's explore some examples of how to achieve this using SQL queries.



1:1 Example: User has One Product | Product belongs to a User

In this scenario, each user has only one product associated with them. We can use the JSON_OBJECT function to create an object containing user details within the product data.

$sql1 = "SELECT products.id, products.name,

      (

          SELECT 

              JSON_OBJECT(

                  'id', users.id,

                  'name', users.name,

                  'email', users.email

              )

          FROM users

          WHERE users.id = products.user_id

) AS users

FROM products";

$results = \DB::select($sql1);

Output:

[

    {

        "id": 1,

        "name": "Marvel Tshirt",

        "users": {

            "id": 1,

            "name": "John Doe",

            "email": "johndoe11@gmail.com"

        }

    },

    {

        "id": 2,

        "name": "Roadster Full sleves tshirt",

        "users": {

            "id": 2,

            "name": "Richard Parker",

            "email": "richard88@gmail.com"

        }

    }

]

1:Many Example: User has Many Products | Product Belongs to User

In this case, each user can have multiple products associated with them. We utilize JSON_ARRAYAGG to aggregate product data into an array within the user object.

$sql1 = "SELECT users.id, users.name,users.email,

    (

        SELECT 

            JSON_ARRAYAGG(

                JSON_OBJECT(

                    'id', products.id,

                    'name', products.name

                )

            )

        FROM products

        WHERE products.user_id = users.id

) AS products

FROM users";

$results = \DB::select($sql1);

Output:

[

    {

        "id": 1,

        "name": "John Doe",

        "email": "johndoe11@gmail.com",

        "products": [

            {

                "id": 1,

                "name": "Marvel Tshirt"

            },

            {

                "id": 3,

                "name": "Hoodies"

            }

        ]

    },

    {

        "id": 2,

        "name": "Richard Parker",

        "email": "richard88@gmail.com",

        "products": [

            {

                "id": 2,

                "name": "Roadster Full sleves tshirt"

            }

        ]

    }

]

Conclusion

JSON structuring within SQL queries provides a flexible and efficient way to handle relational data, especially in scenarios involving 1:1 and 1:many relationships. By leveraging functions like JSON_OBJECT and JSON_ARRAYAGG, we can easily format our data in a way that suits our application's needs.

0 comments:

Post a Comment