0

我在PostgreSQL中構建了一個評論系統,我可以在我已經擁有的不同實體上評論(以及「喜歡」他們)(例如產品,文章,照片和等等)。就目前而言,我想出了這個:針對不同類型的實體的建築評論系統

注: comment_board和產品/條之間的外鍵/拍照非常寬鬆這裏REF_ID只是存儲的ID,這是在配合使用comment_board_type以確定它是表)

Solution 1

顯然,這似乎並沒有想好數據的完整性。我能做些什麼來給它更好的完整性?另外,我知道每件產品/文章/照片都需要評論。莫非意味着我實現comment_board_id各產品/條/攝實體,如本?:

Solution 2

我認識到這一點做方案,但它讓我揣測超類型和它的複雜性: Database design - articles, blog posts, photos, stories

任何指導表示讚賞!

+0

您可能會發現對此有用的繼承(http://www.postgresql.org/docs/current/static/ddl-inherit.html)。 –

+0

@GordonLinoff你認爲產品/文章/照片會繼承comment_board嗎?看起來像postgres繼承的問題之一是它不能對子項進行索引/ FK約束。也許沒什麼大不了的。 我正在考慮將comment_board更改爲「實體」,然後結尾爲:實體(entity_id PK,created_at,updated_at)和產品(id,created_at,updated_at,entity_id)'和comment(id PK,entity_id REFERENCES實體(entity_id),...)''。我不知道該怎麼做的唯一事情就是在事實之後繼承其他表 – Handonam

回答

0

我最終直接將評論指向產品/照片/文章字段。以下是我在總

CREATE TABLE comment (
    id SERIAL PRIMARY KEY, 
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT (now()), 
    updated_at TIMESTAMP WITH TIME ZONE, 
    account_id INT NOT NULL REFERENCES account(id), 
    text VARCHAR NOT NULL, 

    -- commentable sections 
    product_id INT REFERENCES product(id), 
    photo_id INT REFERENCES photo(id), 
    article_id INT REFERENCES article(id), 

    -- constraint to make sure this comment appears in only one place 
    CONSTRAINT comment_entity_check CHECK(
    (product_id IS NOT NULL)::INT 
    + 
    (photo_id IS NOT NULL)::INT 
    + 
    (article_id IS NOT NULL)::INT 
    = 1 
    ) 
); 

CREATE TABLE comment_likes (
    id SERIAL PRIMARY KEY, 
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT (now()), 
    updated_at TIMESTAMP WITH TIME ZONE, 
    account_id INT NOT NULL REFERENCES account(id), 
    comment_id INT NOT NULL REFERENCES comment(id), 

    -- comments can only be liked once by an account. 
    UNIQUE(account_id, comment_id) 
); 

想出了在所得:

enter image description here

這就讓我必須做的少了一個加入到中介表。另外,它可以讓我添加一個字段並輕鬆更新約束。