Posts tagged Zend_Db_Table_Abstract
There has to be an easier way :(
Feb 18th
So I’m working on a project, and I want to find all of the rows that don’t have a row in it’s related table using Zend_Db_Table_Select… Simple right? Not really
. In theory this would be the query that I would write…
SELECT author.id FROM author LEFT JOIN project ON project.author_id = author.id WHERE project.author_id IS NULL ORDER BY RAND() LIMIT 1
After toying with Zend_Table for a while I’ve managed to figure out how to do it…
/**
* Fetches a random author who has not had a project assigned to them
* @return Ambigous <Zend_Db_Table_Row_Abstract, NULL>
*/
public function findRandomNull(){
$authorModel = $this->getDbTable();
$select = $authorModel->select()
->setIntegrityCheck(false)
->from('author')
->joinLeft('project', 'project.author_id = author.id', array())
->where('project.author_id IS NULL')
->order('RAND()');
return $authorModel->fetchRow($select);
}
Which will produce the following SQL
SELECT `author`.* FROM `author` LEFT JOIN `project` ON project.author_id = author.id WHERE (project.author_id IS NULL) ORDER BY RAND() ASC
Non-existant fields Zend_Db_Table_Abstract
Dec 20th
I’d run into a problem in the Zend Table where when inserting data from a form, if a field didn’t exist in the database ZF would crap out with an exception. Having to unset posted variables I didn’t need, meant more typing, more typing meant more unnecessary code.
I found the easiest way to get around this is by overriding the insert method in my extended App_Db_Table_Abstract class. Here’s what my new insert method looks like.
public function insert($data, $skip = true){
if($skip === true){
$oldData = $data;
$data = array();
foreach($this->info('metadata') as $key => $value){
if(isset($oldData[$key])){
$data[$key] = $oldData[$key];
}
}
}
parent::insert($data);
}
The method takes two parameters, the data ($data) and a Boolean value ($skip). Skip defaults to true, so I don’t need to add this parameter to every call to insert, it’s also there in case I don’t want to skip my data.
It then iterates through the table meta data, which contains the field names for the table, checks to see if the key exists in the data from the form. If the field exists in the array then it’s added to the new data array.
Finally the parent insert method is called, bobs your uncle.
In case you’re wondering, I’ve subclassed some of the Zend classes, this allows me to override methods to my liking.