On Mar 7, 2011, at 14:03, Zaky Katalan-Ezra wrote: > On Mon, Mar 7, 2011 at 8:50 PM, Ryan Schmidt wrote: >> On Mar 7, 2011, at 12:34, Zaky Katalan-Ezra wrote: >> > On Mon, Mar 7, 2011 at 1:43 PM, Krissy Masters wrote: >> >> Since only 1 field can be auto-inc, that’s not really the best solution. >> >> >> >> I would suggest to update 1 field where CONDITION >> >> >> >> In the view function add in something like: >> >> >> >> $this->Model->updateAll( array( 'Post.view_count' => 'Post.view_count + 1' >> >> ), array( 'Post.id' => $post['Post']['id'] ) ); >> > >> > This solution raise another issue. >> > If two users get the data at the same time but update the data one after >> > another you end up with equal value in two rows. >> >> I don't think that problem exists here. Using updateAll() should generate a >> single UPDATE SQL statement, which should be atomic. > > Even though updateAll is atomic the problem exist. > User A and user B fetch the data at 10:00 and have Post.view_count = 9 > User A click the submit button at 10:02 and user B at 10:03. > They both update view_count = 10
I understand the problem you're describing, but the posted code does not exhibit that problem. The posted code executes the single following SQL statement (if $post['Post']['id'] is 5): UPDATE `posts` AS `Post` SET `Post`.`view_count` = Post.view_count + 1 WHERE `Post`.`id` = 5; This is atomic. The data is not fetched at 10:00 as you say. (At least, not in any code that was shown.) The data is fetched from the database and immediately updated in the database the instant the UPDATE query runs at 10:02 and 10:03 by each user. Each time this SQL statement is executed, view_count will be increased by one in the database. There is no race condition and no risk of the problem you describe. There are certainly examples of race conditions like the one you describe posted on this list on a daily basis, but this is not one of them; this is an example of how to avoid that problem and do it correctly. -- Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions. To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/cake-php
