0

Hi Guys this may seam a bit of a strange question but here goes:

This is just a basic example so you can understand what I am trying to achieve.

If I have a mysql database with two tables: "liquid_avaliable" and "liquid_records". liquid avliable would have 3 columns id, name, amount. liquid_records would have id, name, amount_used, liquid_avaliable_id.

Would it be possible to everytime a "liquid record" is added that the amount is subtracted from the avaliable table enrty.

The purpose is so you could just do a quick check on the liquid avaliable table to see how much of each you have left.

If anyone could point me in the right direction it would be much appreciated.

The app I'm working on is built in "cakePHP" and my database system is mysql although Postgre sql is also avliable.

Thanks in advance.

4

2 に答える 2

1

You have several ways of solving this problem.

(1) You could do nothing, and calculate the amount available at run-time. This can be an acceptable solution, for reasonable hardware and moderately sized data. Performance should be reasonable even up to hundreds of thousands of rows.

(2) The canonical database solution is to use triggers. Create a trigger on the "liquid record" table. When a new record is added, subtract or add the amount from the other table.

(3) Do all insertions into the table using a stored procedure. This is my preferred method. The stored procedure can then increment or decrement other values (as well as doing logging and other operations if desired).

I would suggest that you wrap all your data operations into stored procedures, but proceed with (1). Write a query to get what you want from the data structure. Add indexes as appropriate. If this doesn't work then proceed to (3).

于 2012-11-09T20:19:25.897 に答える
1

Yes - you can use the afterSave() callback method.

It will automatically get triggered when LiquidRecord is saved - at that point you can add the logic to re-calculate and save the new total to your LiquidAvailable model.

Another option is to look into CakePHP's Event System.

于 2012-11-09T20:41:45.190 に答える