訂單金額使用固定四欄位:items_subtotal、discount_total、shipping_fee、total
我看過很多團隊,他們價格相關的欄位設計亂七八糟。為了得到訂單的總價,有時候幾個欄位要相加,有時候要相減。上線之後,code 就很難讀,bug 也一大堆。
我分享一組很簡單、卻很有效的命名跟資料型態。你用四個欄位去表達就好了:
items_subtotal
discount_total
shipping_fee
total
這些欄位的類型都用 unsigned integer 就可以。
背後的數學就是:
total = items_subtotal - discount_total + shipping_fee
那個 total,就是實際跟客戶收的金額。
然後,除了 orders table 之外,另外會有一張 order_items table。那個 order_items 裡面,就有訂單裡面有哪些商品的細項。
每一個 order item 都有自己的 unit_price quantity subtotal 欄位。所以,一張訂單的所有 order items,把全部的 subtotal 相加,就會是 orders.items_subtotal 這個欄位。
這些欄位都用 unsigned integer 就可以了,不需要再有負數或其他額外的理解。這樣子很簡潔,可以減少誤會,系統也容易維護。
不要再用一些奇怪的單字,像是 final total、total price 之類的名稱。這些都不需要,用我這組命名就是最精準的。