I have to create a GET type of API and I have to connect two tables.
For example, I have the following tables:
Table 1:
Table 2:
If I connect the two tables I get the following result:
{
"customer_id": 001,
"first_name": "f_name",
"last_name": "l_name",
"street": "A street",
"zip_code": "1234",
"city": "xxxx",
"country": xx
}
{
"customer_id": 001,
"first_name": "f_name",
"last_name": "l_name",
"street": "B street",
"zip_code": "1234",
"city": "xxxx",
"country": xx
}
This is beacuse the table2 has two rows with the customer_id:"001".
But I want this kind of result:
{
"customer_id": 001,
"first_name": "f_name",
"last_name": "l_name",
"address": [
{
"street": "A steet",
"zip_code": "1234",
"city": "xxxx",
"country": xx
},
{
"street": "B street",
"zip_code": "1234",
"city": "xxxx",
"country": xx
}
]
}
It seems like a simple query won't work here. Has anybody ideal how should I create this GET type of API?
This can be created using a simple SELECT
statement for your GET API. You need to use the CURSOR
command to create nested arrays within your JSON object. An example of what you need can be seen below.
:p_customer_id in the example below is some sort of input parameter from your API.
SELECT t1.customer_id,
t1.first_name,
t1.last_name,
CURSOR (SELECT t2.street,
t2.zip_code,
t2.city,
t2.country
FROM table2 t2
WHERE t2.customer_id = t1.customer_id) AS address
FROM table1 t1
WHERE t1.customer_id = :p_customer_id;