簡體   English   中英

交易目的地外鍵的在線信用系統表布局

[英]online credit system table layout for transaction destinations foreign key

我試圖弄清楚當鍵基於類型指向不同的表時如何正確存儲外鍵。

我進行了搜索,但發現似乎沒有任何幫助

有一個表將存儲學分的大部分基礎知識:

user_accounting
--------------------
user_accounting_id      (PK)
user_id                 (FK)
amount              
type                    (+deposit, +credit, -transfer, -purchase)
credit                  (bool, so I don't have to always check if amount is < or > 0)
void                    (in case it was canceled and repaired with some other transaction)
date
details                 (notes)

類型s:

deposit - for outsite money being put into the system.
credit - are for money being transfered into their account from another
transfer - for putting money into someone elses account
purchase - for purchasing a site item

到目前為止,一切都很好。 下一部分我有點困惑。 它還必須存儲資金的去向或來源。

我想存儲表明它來自的任何類型的外鍵。 因此,如果是購買,它將存儲invoice_id的FK,如果是存款,它將存儲來自商家提供商的transaction_id,如果是轉賬,它將存儲信用的user_accounting_id,如果是信用,它將存儲存儲轉賬的 user_accounting_id。

我會很高興有一個單列存儲:

user_accounting (con't)
-----------------------------
source_or_destination_id (FK)

但我知道我不能讓單個列成為基於type鏈接到不同表的外鍵。 所以我可以將它存儲為 (int) 但嘗試使用該 id 與基於type的不同表進行 JOIN 將是一個巨大的痛苦 很久以前就嘗試過,大錯特錯。

所以相反,我可以這樣做:

user_accounting (con't)
-----------------------------
invoice_id                  (FK)
transaction_id              (FK)
credit_user_accounting_id   (FK)
transfer_user_accounting_id (FK)

但是這又是一個大問題,因為我創建了一個不好的獨家弧。

我也可以對類型使用 many_to_many_through 關系,但是 pivot 表仍然存在將外鍵存儲在多個表的同一位置的相同問題。

也許我可以簡單地將不同類型的事務完全存儲在不同的表中,我可以:

user_accounting_deposit, user_accounting_credit, user_accounting_transfer, user_accounting_purchase.

然后外鍵就不會有問題了。 當然,要弄清楚任何人的帳戶余額,我現在必須從一堆表中進行連接和求和。

也許有一種完全不同的更好的方法來做到這一點。 我不在乎它需要多少張桌子。 我很可能在某處使某些事情復雜化了。

謝謝

500 多年來,簿記員一直在處理存儲資金的來源和去向的問題。 這就是他們發明復式記賬法的原因。 否則稱為復式記帳。

您需要查看用於復式記賬的數據 model。 在您之前的程序員已經這樣做了數千次。

如果您需要樣品 model,請訪問數據庫答案並查看“會計系統”。 您應該能夠獲得涵蓋您的案例的 model 圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM