I currently have the following SQL database:
CREATE TABLE `users` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(40),
`email` VARCHAR(40),
PRIMARY KEY (`id`)
);
CREATE TABLE `widgets` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`production_date` DATETIME,
`title` VARCHAR(100),
PRIMARY KEY (`id`)
);
CREATE TABLE `users_widgets` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`user_id` INT(11),
`widget_id` INT(11),
PRIMARY KEY (`id`)
);
ALTER TABLE `users_widgets` ADD CONSTRAINT `users_widgets_fk1` FOREIGN KEY (`user_id`) REFERENCES users(`id`);
ALTER TABLE `users_widgets` ADD CONSTRAINT `users_widgets_fk2` FOREIGN KEY (`widget_id`) REFERENCES widgets(`id`);
Users HABTM widgets. Basically, in this scenario, I need to figure out, for each user, how many widgets in a row that user paid for. Widgets should be ordered by production_date in order to figure out whether or not they are "consecutive" and widgets are not produced every day, but a widget produced on Feb 3d and a widget produced on Feb 11th could be consecutive, as long as no widgets were produced Feb 4-10.
This is how the site works: The site owner places a number of widgets up on the site, and users can pledge money towards the widget. The amount they pay will always be $1. Once enough users have paid for a widget, the widget is produced and a production_date is added to the widget.
What I am trying to implement is essentially a customer loyalty program. How many consecutive widgets that were put into production did the user buy? Then I can, say, offer a coupon or a discount for users that bought X widgets in a row. Each user can only pay for a widget once, but can pay for multiple widgets, some in production and some not. Widgets that are not in production (production_date=null) should not affect the calculation of consecutive widgets.
Auto-increment doesn't really work here, because widgets may be put into production in a different order than the database record was initially created. So, I need to order the widgets by production_date in order to determine which widgets are consecutive.