Smart save on Zend_Db_Table objects
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 38 39 4041 42 43 44 4546 47 48 49 | class My_Model_Table extends Zend_Db_Table { //... /** * Smart save * * @param array $data Associative array with row data. * @return mixed Primary key value. */ public function save($data) { $this->_setupPrimaryKey (); //method inherited from parent class(Zend_Db_Table_Abstact) $cols = array_intersect_key ( $data, array_flip ( $this->_getCols () ) ); // _getCols() - inherited from parent if (array_intersect ( ( array ) $this->_primary, array_keys ( array_filter ( $cols ) ) )) { //possible update if (is_array ( $this->_primary )) { //composed Pk $a = array (); foreach ( $this->_primary as $pk ) { $a [] = $cols [$pk]; } if (count ( $this->_primary ) == count ( $a )) { //eval(sprintf('$rows = $this->find(%s);', implode(', ', $a))); $rows = call_user_func_array ( array ($this, 'find' ), $a ); } else { throw new Zend_Db_Table_Exception ( 'Invalid primary key.(Primary key is composed, but incomplete)' ); } } else { $rows = $this->find ( $cols [$this->_primary] ); } if (1 == $rows->count ()) { // only one record $pk =$rows->current ()->setFromArray($cols)->save(); } elseif (0 == $rows->count ()) { // or might want to insert a row with a certain id(like when you doing imports) $pk = $this->insert ( $cols ); } else { throw new Zend_Db_Table_Exception ( 'Error updating requested row.(More than 1 row or invalid Id?!)' ); } } else { //new row $pk = $this->insert ( $v = array_diff_key ( $cols, array_flip ( ( array ) $this->_primary ) ) ); } return $pk; } //... } |
1
2
3
4
56
7
| /*some action from your action-controller */ ... $myModel = new My_Model_Table(); $data = array('foo' => 1, 'bar'=> 2); $myModel->save($data); //doing an insert$data2 = array('id' => 1, 'foo' => 2, 'bar' => 2); $myModel->save($data2); //possible update...if row with id = 1, exists |
Comments
You must login before commenting on a snippet. If you do not have an account, please register.
Snippet description
Method to help save the data, in objects of type Zend_Db_Table, depending on context (insert / update). It is treated and the case if the primary key can be composed, but not tested:). Also, the orphan data is skipped.
Snippet details
- Created:
-
zailic
- Edited:
-
zailic
- Revision Id:
- 79
- Edit Message:
- Initial Release
- Tags:
- Zend_Db_Table insert update save
- Comments:
- 3
- Views:
- 256
- Points:
- 0 (0 votes)
1 year ago
Like as bin and store methods in joomla db table class. Nice class, nice job ^^