Take snapshot of DB table row? - php

I want to take a snap shot of a row in a MySQL table.
The reason being, if someone buys a product. I want to take a snapshot of that product to store for the order.
It needs to be a snapshot to maintain data integrity. If I just assign the product to the order, if the product changes in the future the order will show those changes. For example if the price changes, the order will now load the new data and say that it sold the product at its new price rather than what the price was when the order was placed. So a snapshot needs to be assigned to the order instead.
The way I did this in the past was having 2 tables, one for products, and one for snapshots of products. The snapshot had every column as the regular table plus extra colums like order_id
I had a script to take a snapshot that automatically looked at the fields in the regular table and tried to do an insert into the same fields into the snapshot table.
The biggest problem with that approach is that, if I added a column to the regular table and forgot to add the same column to the snapshot table; the script would try to insert data into a non existent field and fail.
I also disliked the idea of having 2 tables that were nearly identical. I think maybe figuring out a way to use one table for both purposes might be better.
So I am wondering if there is a known method I am unaware of to solve this issue?
My previous project used no framework but my next one will be using CakePHP if that matters.

I think the best way of handling this would be to roll the "snapshot" information into an orders_products table. So if you have an order, store the total price, tax, etc. information in a single row on the orders table and reference that order_id on your orders_products table. On your orders_products table, you can have order_id, product_id, price, quantity, discount and whatever else you need.

Seems like your previous is fine. But that you just need to do more testing to ensure that you don't forget to add the new fields to the snapshot table. Seems like a basic test that would be easy to do. The other alternative is to just use a big text field, and store the snapshot as XML. This will let you store the snapshot regardless of if the schema changes. Depending on how much you want to query this data, it may or may not work for you.
Also you may not want to store every field, as it may just take up extra space. For instance, if you have the location of the image file of the item, you may not want to store that, as it may not be important at a later date. You could try querying information_schema to query which fields are in the snapshot table, and only copy the available fields.

Related

Laravel - DB structure change - Is this a good practice or not?

Hello how are you? I wanted to ask you who have more experience than me if what I want to do is a good or bad practice in Laravel.
I am making an ordering app and in my database I have that a product has a certain price (one more field in the product table). But then I realized that when the price of the product one day changes, the price will also change in an old order, that is, the old order will adopt the new price of the product at this moment and not on the date when the order was placed, thus generating an information problem.
For that, I decided to create a new table that has the temporary prices, that is, if the price changes, that a new row is created in the database with the price on a certain date, but that the price it had in another is recorded. date.
Now, my question is ... How can I bring the current price of a product to that new table that I am creating, without the user intervening ... that is, migrate all the prices of each product to that new table.
My idea was to create a function that goes through each product and that creates a new row in the prices table with the product id, the price and the current date. Once this function is created, run it through Tinker and that the user does not notice absolutely nothing, but that the system adopts the new price structure.
This is good?
Is it a good practice or is there a better way to do it?
Thank you.
welcome to SO! This is one possible way to do it to have a table with the price history incl. start and end date of validity. To not overcomplicate the queries for showing the user his order history I would recommend you also to save the price of the product in the order. For example in the many-to-many mapping table between order and product, where you can also save the amount of the purchased products.
You could make a CLI command (e.g. php artisan make:command InsertOrderPrices) then to fill these fields for the old orders after you created them.

update record, or delete and re-insert if the user edits their cart before processing the order

I have a table named orders_products which hold all the products associated with each individual orders. Now, if the customer decides to edit the quantity, the attributes, or simply just remove a product, what would be the easiest way to handle this change in the database?
orders_products
id | quantity | fk_products_id | attributes | price | fk_orders_nr
fk_products_id refers to the actual product id in our products table
attributes is a comma sepparated string with id's refering to our attributes table (attributes can be the angle, lenght, diameter etc. for each product. As in 45 degres, left angeled, 20 cm in length, 43mm in diameter).
fk_orders_nr is the actual order the product belongs to.
Since I have a class that handles this part on the client side. Would it be easier to just DELETE all associated products, based on the order id (fk_orders_nr), and just re-insert and updated the whole set based on what's stored in the class?
Or is there a neat way to handle this directly in MySQL?
I've looked a bit into on duplicate key update, and ignore, but they doesn't seem to fit my needs..
I need to check to see if the actual product id exists, then decide to insert new, or update existing (it could be both the quantity, and/or optional attributes), also the product might be removed if not in the list from the class anymore.
When writing this question. I think deleting the whole set, and reinsert it, might be the easiest way.
This database looks badly designed. Firstly I assume by fk_products_id you mean product_id. You do not need to specify that a column is a foreign key in its name.
Secondly, I would advise you to keep all columns atomic, as in, no multi-values. The attributes column keeping a comma-separated list will give you headaches in the future and it also breaks the FIRST normal form (the most basic one).
Thirdly, you don't need (although it could sometimes be useful) an id as a primary key in your junction table. You can just use a compound primary key from your fk_products_id and fk_orders_nr keys.
When writing this question. I think deleting the whole set, and
reinsert it, might be the easiest way.
Yes, that is the way it's usually done.
But I insist you ignore everything about the current problem you're having and redesign your database from scratch, putting special attention into normalization. These are basic database design standards and they exist for a reason. Hopefully you won't learn about the reason when it's too late.

Data model for subscriptions, single purchase products and variable services

I am designing a database for a system that will handle subscription based products, standard one off set price purchase products, and billing of variable services.
A customer can be related to many domains and a domain may have many subscriptions, set priced products or billed variable services related to it.
I am unsure whether to seperate each of these categories into their own 'orders' table or figure out a solution to compile them all into a single orders table.
Certain information about subscriptions is required such as start date or expiry date which is irrelevant for stand alone products. Variable services could be any price so having a single products table would mean I would have to add a new product which may be never used again or might be at a different cost.
What would be the best way to tackle this, and is splitting each into seperate order tables the best way?
Have you looked at sub-typing - it might work for you. By this I mean a central "order" table containing the common attributes and optional "is a"/one-to-one relationships to specific order tables. The specific order tables contain the attributes specific only to that type of order, and a foreign key back to the central order table.
This is one way of trying to get the best of "both" worlds, by which I mean (a) the appropriate level of centralisation for reporting on things common and (b) the right level of specialisation. The added nuance comes at the cost of an extra join some times but gives you flexibility and reporting.
Although I am a little biased in favour of subtypes, some people feel that unless your order subtypes are very different, it may not be worth the effort of separating them out. There is some seemingly good discussion here on dba.stackexchange as well as here. That being said, books (or chapters at least) have been written on the subject!
As with any data model, the "best" way depends on your needs. Since you don't specify a lot of details regarding your specific needs, it's difficult to say what the bets model is.
However, in general you need to consider what level of detail is necessary. For example if all subscriptions cost the same and are billed on the 1st of the month, it may be sufficient to have a field like is_subscription ENUM ('Y', 'N') in your orders table. If billing dates and prices for subscriptions can vary however, you need to store that information too. In that case it may be better to have a separate table for subscriptions.
Another consideration is exactly what an "order" represents in your model. One interpretation is that an order includes all the purchases included in one transaction, including both one-off purchases, variable services and subscriptions. A completed order would then result in a bill, and subscriptions would be automatically billed on the proper day of the month without a new order being made.
You should aim to have one database design that is not hardwired into specifics regarding its contents, and if it does (have to) it does in such a way that it seperates the specialization from the core DB design.
There are certain fields that are common for each order. Put these in one table, and have it refer to the other rows in the respective (specialized) tables. Thats DB normalization for you.
You could have main table contain ID, OrderID, ItemType, ItemID when ItemType determines the table ItemID refers to. I advise against this, but must admit that i use this sometimes.
Better would be to have these tables:
Clients: ID, Name, Address, Phone
Sellers: ID, Name, CompanyAlias
Orders: ID, ClientID, SellerID, Date, Price
OrderItems: ID, OrderID, DiscountAmount, DiscountPercentage,
ProductDomainID, ProductBottleID, ProductCheeseID, ..
Now OrderItems is where the magic happens. The first four fields explain themselves i guess. And the rest refers to a table which you do not alter or delete anything ever:
Products_Cheese ID, ProductCode, ProductName, Price
And if you do need a variant product for a specific order add a field VariantOfID thats otherwise NULL. Then refer to that ID.
The OrderItems table you can add fields to without disturbing the established DB structure. Just constrict yourself to use NULL values in all Product*ID fields except one. But taking this further, you might even have scenario's where you want to combine two or more fields. For example adding a ExtraSubscriptionTimespanID or a ExtraServicelevelagreementID field that is set alongside the ProductCheeseID.
This way if you use ProductCheeseID + ExtraSubscriptionTimespanID + ExtraServicelevelagreementID a customer can order a Cheese subscription with SLA, and your database structure does not repeat itself.
This basic design is open to alterative ideas and solutions. But keep your structure seperated. Dont make one huge table that includes all fields you may ever need, things will break horribly once you have to change something later on.
When designing database tables, you want to focus on what an entity represents and having two or more slightly different versions of what is essentially the same entity makes the schema harder to maintain. Orders are orders, they're just different order types for different products, for different customers. You'd need a number of link tables to make it all work, but you'd have to make those associations somehow and it beats having different entity types. How about this for a very rough starting point?
What would be the best way to tackle this, and is splitting each into seperate order tables the best way?
That depends. And it will change over time. So the crucial part here is that you create a model of the orders and you separate the storage of them from just writing code dealing with those models.
That done, you can develop and change the database structure over time to store and query all the information you need to store and you need to query.
This for the general advice.
More concrete you still have to map the model onto a data-structure. There are many ways on how to solve that, e.g. a single table of which not all columns are used all the time (flat table), subtype tables (for each type a new table is used) or main table with the common fields and subtype tables containing the additional columns or even attribute tables. All these approaches have pros and cons, an answer here on Stackoverflow is most likely the wrong place to discuss these in full. However, you can find an insightful entry-level discussion of your problem here:
Entity-Attribute-Value (Chapter 6); page 61 in SQL Antipatterns - Avoiding the Pitfalls of Database Programming by Bill Karwin.

The right database structure and model relations in CakePHP for my project (small shop)?

I have a pretty simple shop-system. I'm working with CakePHP. Actually I wouldn't call it shop, it's rather a basic form where you can type in your data and which items in which color you want and that's it.
There is one buying-form which is "open to the public" and then there are buying-forms which are password secured.
The latter ones have a selection of the items (or selection of colors) which you get on the public site, but have discounts.
I want to save the orders in a database. I have a table orders and ordered_products. That's working fine.
It works pretty good, but only because I made something not very good: Since there are just a few products I just wrote an array in the controller with the names, prices and stuff... the discounts or selection of products I handled by just overwriting the products-property.
Well, putting data in the controller is not really the idea behind the MVC-Structure, so I was thinking about who to handle the products, the selection of products for the different password-secured buying forms and the discounts with models.
My idea was, to create the following tables:
products (id, name, price,...) -hasAndBelongsToMany Color
colors (id, name)
products_colors (product_id, color_id)
Now to set in which "closed-area", which products in which color and with which special price can be ordered I thought of the following tables (the actual table and field names are of course not wise chosen, but just for the idea):
product_selections (id, closed-area_name, product_id, special_price) hasAndBelongsToMany Color
product_selections_colors (product_selection_id, color_id)
When I'm creating the public buying form I would just use the top three tables. but building the "closed-area" I would use the bottom two, selecting the product_ids and special_prices from product_selection as well as the different colors over the product_selections_colors-table for the according "closed-area" (i dont know a better name for that right now...). with the product_id i would get the other information about the product from the table products and create the buying form with this data.
I want to have it all in a database, because then I can better work with the orders (creating receipts, deliverynotes etc.).
I would like to know what you think about that, because I have the feeling that I'm going totally in the wrong direction, since it feel way to complicated for such a simple thing...
I hope you can help me.
Based on your description, I would recommend doing it this way:
Have a users table with a field for "group_id". This allows you to have multiple users with login privileges that all can view the same options or colors based on their grouping.
In the case of a general (non-logged in) user, the assign the group_id to default to 0.
Next, ditch the product_selections and product_selections_colors tables.
You don't want to have to repeat products across tables.
Simply add a new table that pairs which product ids can be purchased by which group_ids. (HABTM relationship in cake)
You will obviously need to tweak this general setup to work specifically for your needs.

Magento Order Table: custom column

I recently made a module that calculates the real gross margin for every order and order_item based on shipping cost data I import. I did this by adding 2 columns to the sales_flat_order table and the sales_flat_order_item table. This seemed to work great, until I realized that when I saved the imported data, it also updated the updated_at value. Since this was the first import of all orders, they all now report having been updated today. This is throwing off reports and other shipping software that syncs with it.
This brings me to 2 questions:
Is adding a column to an existing table (in this case, the sales tables) a major NO-NO?
If not, is there a way to set the data that doesn't increase the updated_at value?
If it helps, the code that actually writes the data is inside my IndexController.php file. It loops through the collection of orders and the items within those orders and sets the necessary values using something like $order->setGrossMargin($orderGM)->save();. I imagine it is the call to save() that is doing it, but I'm not sure the right way around this problem.
In the mean time, I'm working on a solution in which I import the data to custom tables and only read from the sales tables when necessary. Either way, it's a good exercise :)
Brian
Instead of calling save(), did you try:
$order->getResource()->saveAttribute('gross_margin')

Categories