php - Update "Properties" model when adding a new record in CakePHP -
i'm writing application in cakephp that, now, used make quotes customers. quote model. want have separate model/table "property," may used other models.
each time user gets "add quote" action, want pull property called "nextquotenumber" or along lines, , automatically increment property, even if new quote isn't saved. don't think using autoincrement quote's id appropriate here - also, "quote number" different row's id.
i know simple enough do, i'm trying figure out "proper" cakephp way of doing it! i'm thinking should have method inside property model, "getproperty($property_name)", pull value return, , increment value... i'm not sure best way of doing is, or how invoke method quotes controller.
what should do? in advance!
i ended doing bit more specific, making model 'sequence' rather more general 'property'. sequence has 3 fields: id, name, value. since need sequence quotes starting 1001, there's 1 row (1, 'quote', 1001).
in model file sequence.php following:
class sequence extends appmodel { var $name = 'sequence'; function getnext($sequencename) { // make transaction, 2 concurrent requests can't same value. $this->begin(); // find sequence given object, let's 'quote' $row = $this->find('first', array( 'conditions' => array('sequence.name' => $sequencename), 'fields' => array('id', 'value'), )); // save original value (before incrementing) can return it. $value = $row['sequence']['value']; // update value in database. $row['sequence']['value'] = $value + 1; $this->save($row); // commit changes database, ending lock. $this->commit(); return $value; }
as webbiedave pointed out, atomicity required or it's possible 2 users/quotes same sequence number, hence begin() , commit() calls.
then, in quotes_controller, added following in add() action:
$this->loadmodel('sequence'); $quotenumber = $this->sequence->getnext('quote');
then can use $quotenumber wish.
hope helps somebody, , please contribute if there's better way of doing it. thanks!
Comments
Post a Comment