Skip to main content

建立表與表之間的關聯

在之前的過程中,已經建立了request以及command,而預計的規劃是可以透過一個command來觸發多個request的功能,而且多個command可以觸發同一個request,而觸發的順序可以自己定義,那要完成這個需求,預計要多開一張表,名為commands_requests,而這張表的主要目的是要將commands跟requests建立起關聯,因此目前規劃的欄位有

nametype
uuiduuid
commands_uuiduuid
requests_uuiduuid

另外,因為需要有觸發順序,所以欄位中要多上一個順序的欄位

nametype
uuiduuid
commands_uuiduuid
requests_uuiduuid
orderint

並且

commands_requests.commands_uuid <= command.uuid
commands_requests.requests_uuid <= requests.uuid

將相關的欄位做foreign key的關聯,這樣做就可以讓資料庫來幫我們保證在commands_requests中的兩個uuid都一定存在於另外兩張表中

資料庫語法如下

CREATE TABLE public.commands_requests  
(
uuid uuid NOT NULL DEFAULT uuid_generate_v4(),
create_at timestamptz NOT NULL DEFAULT now(),
update_at timestamptz NOT NULL DEFAULT now(),
commands_uuid uuid NOT NULL,
requests_uuid uuid NOT NULL,
"order" int8 NOT NULL,
CONSTRAINT commands_requests_pk PRIMARY KEY (uuid),
CONSTRAINT commands_requests_fk FOREIGN KEY (commands_uuid) REFERENCES public.commands (uuid) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT commands_requests_fk_1 FOREIGN KEY (requests_uuid) REFERENCES public.requests (uuid) ON DELETE SET NULL ON UPDATE CASCADE
);

另外,因為有發現到之前的commands跟requests並沒有primary key,所以也將建立Primary Key的語法補上去

ALTER TABLE public.commands  
ADD CONSTRAINT commands_pk PRIMARY KEY (uuid);
ALTER TABLE public.requests
ADD CONSTRAINT requests_pk PRIMARY KEY (uuid);

最後,因為怕在自動產生uuid的extension在postgresql中沒建立,所以將建立這個extension的功能也放上

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

另外,也補上了之前沒寫到的down檔

影片和code如下

https://www.youtube.com/watch?v=ScRe3zVh8-E

https://github.com/kevinyay945/smart-home-backend/tree/0442b034cb84a31bbb59858f70f64a5aa871578f