我必須創建一個 GET 型別的 API,并且我必須連接兩個表。
例如,我有以下表格:
表格1:
- 客戶 ID:{001}
- 名字:{f_name}
- 姓氏:{l:name}
表 2:
- 客戶 ID:{001} {001}
- 街道:{A 街道} {B 街道}
- 郵編:{1234} {1234}
- 城市:{xxxx} {xxxx}
- 國家:{xx} {xx}
如果我連接這兩個表,我會得到以下結果:
{
"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
}
這是因為 table2 有兩行 customer_id:"001"。
但我想要這種結果:
{
"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
}
]
}
似乎一個簡單的查詢在這里不起作用。有沒有人理想我應該如何創建這種 GET 型別的 API?
uj5u.com熱心網友回復:
這可以使用SELECT您的 GET API 的簡單陳述句來創建。您需要使用該CURSOR命令在 JSON 物件中創建嵌套陣列。您需要的示例如下所示。
以下示例中的 :p_customer_id 是來自您的 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;
uj5u.com熱心網友回復:
我們將在查詢中使用 CURSOR。
首先是表格和資料:
CREATE TABLE CUST (
CUSTOMER_ID INTEGER,
FIRST_NAME VARCHAR2(20),
LAST_NAME VARCHAR2(20)
);
ALTER TABLE CUST
ADD CONSTRAINT CUST_PK PRIMARY KEY (
CUSTOMER_ID
);
CREATE TABLE ADDY (
CUSTOMER_ID INTEGER,
STREET VARCHAR2(20),
ZIPCODE VARCHAR2(5),
CITY VARCHAR2(20),
COUNTRY VARCHAR2(20)
);
ALTER TABLE ADDY
ADD CONSTRAINT CUST_ID FOREIGN KEY
(
CUSTOMER_ID
)
REFERENCES CUST
(
CUSTOMER_ID
)
ON DELETE CASCADE
NOT DEFERRABLE NOVALIDATE
;
insert into CUST values (1, 'Jeff', 'Smith');
insert into addy values (1, 'Chowning Place', '00001', 'Blacksburg', 'USA');
insert into addy values (1, 'Inkberry Ct', '00002', 'Apex', 'USA');
然后我們可以構建 REST API。
我們的模板是 cust_address/:id,我們將對其進行 GET。
GET 處理程式背后的 SQL:
select customer_id,
first_name,
last_name,
CURSOR(
select street,
zipcode,
city,
country
from ADDY O
where C.customer_id = O.customer_ID
) address
from CUST C
where customer_id = :id
綜上所述,我們的 TEMPLATE/HANDLER 組合在 ORDS 中是這樣定義的(如 SQL Developer Web 中所示)

然后我們呼叫 API - 就在我們的瀏覽器中:

您需要為集合查詢關閉分頁(設定為 0),或者您需要將處理程式定義為集合項。
免責宣告:我是 Oracle 員工,也是 Oracle REST 資料服務的產品經理。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455643.html
