简体   繁体   中英

Payment table that has origin of the sales, orders or no

What is the best way to organize this Payment table:

Right now this is my payment table:

Payments Table

  • PaymentID (primary key)
  • Type (ENUM -> Order, Sale, Payment)
  • Order_id (related to Orders table)
  • Sale_id (related to Sales table)

Example:

PaymentID | Type    | Order_id | Sale_id
1         | Sale    | NULL     | 3
2         | Order   | 2        | NULL
3         | Payment | NULL     | NULL         << In this case, it references itself

So, the question is: is my tables structured correctly? because it will be a problem if I need to take maintenance.

Assuming the id s all have the same type, your structure is redundant. Despite this, yours is probably fine. There are alternatives:

You could do:

PaymentID (primary key)
Type (ENUM -> Order, Sale, Payment)
relatedto_id

The downside is that you don't have a correct foreign key relationship. The upside is that you can add new types without changing the structure of the table. And the records are smaller.

You can also have separate id's for each type:

PaymentID (primary key)
Order_id (related to Orders table)
Sale_id (related to Sales table)

You can then impute the type, perhaps by using a view to access the table. The downside is that adding new types requires modifying the table and you have to impute the type. The upside is that the foreign keys are aligned.

Your structure is fine. However, a downside to using MySQL is that you cannot easily enforce the constraints on the table that make the columns consistent (so a type of "order" would always have a non-null order_id ).

I suggest that your design is incomplete. Consider:

  • What are you going to do when a payment applies to multiple orders
  • What about a payment that applies to only part of an order
  • What if you have a partial payment followed by one that applies to that partially paid order and three others?

The relationship between payments and orders needs to be in a separate table, like "PaymentAllocation" so that you can handle any possible allocation. Also consider that people don't pay for orders, they pay against invoices which may contain multiple orders, and you aren't modeling this at all (unless "Sale" is really "Invoice")

You need, at a minimum:

Order (Order Id, other order data)
Payment (Payment Id, other payment data independent of sale or order)
Sale (Sale Id, I'll assume this is really "Invoice")
PaymentAllocation(PaymentId, SaleId, AmountAllocated)

Note there's no allocation of payments to orders. Payments are allocated to Sales (Invoices).

This is just a rough skeleton to get you thinking about how to model the realities of billing and collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM