Hey,
I have a zend app that displays a league table of race results. The basic process is to determine the list of events to be included, and then dynamically add a set of columns to a SQL query. My initial implementation is rather rubbish and i want to refector it. I manually build up a string of SQL and at the very end call db->fetch(). I know - crap code, but i was still learning zend and had a deadline.
public function league()
{
...
$SQL = 'SELECT rr.runner AS runnerid, ru.firstname as firstname, ru.surname as surname, ';
// get the list of events
foreach($events as $eventrow)
{
$eventTable = new Model_DbTable_Event();
$event = $eventTable->find($eventrow->event)->current();
// generate the conditional column
$sum = $this->getEventSQL($event,$division->gender);
// append to the SQL string (nasty)
$SQL = $SQL . $sum;
}
$SQL = $SQL . 'lrd.racesComplete, lrd.pointsTotal, c.name as company ';
$SQL = $SQL . 'FROM raceresult rr ';
$SQL = $SQL . 'JOIN runner ru ON rr.runner = ru.id ';
$SQL = $SQL . 'LEFT JOIN company c ON c.id = ru.company ';
$SQL = $SQL . 'JOIN race ra ON rr.race = ra.id ';
...
...
$db = Zend_Db_Table::getDefaultAdapter();
$this->view->leaguetable = $db->fetchAll($SQL);
}
// create the SUM sql statement for a specific event
// SUM(CASE rr.race WHEN 15 THEN rr.points ELSE NULL END) as Result1,
// SUM(CASE rr.race WHEN 16 THEN rr.points ELSE NULL END) as Result2,
function getEventSQL($event,$type)
{
$eventTable = new Model_DbTable_Event();
$sum_sql = 'SUM(CASE rr.race ';
foreach($races as $race)
{
$sum_sql = $sum_sql . sprintf('WHEN %d',$race->id) . ' THEN rr.points ';
}
$sum_sql = $sum_sql . sprintf('ELSE NULL END) as \'%s\',',$event->id);
return $sum_sql;
}
I know i need to use the SQL SELECT/CASE statements.
I want to move this logic to a class that extends Zend_Db_Table_Abstract but i'm still unsure what is the best way to conditionally control the columns that are selected. I know i can add multiple where() clauses, can the column() method be used in this scenario?
class Model_DbTable_League extends Zend_Db_Table_Abstract
{
protected $_name = 'leaguerunnerdata';
protected $_primary = 'Id';
public function leagueTable($min,$max)
{
$sql = $this->select()
->setIntegrityCheck(false)
->from(array('l'=>'league'),array('col','col2','col3'))
->where('l.league = ?',1)
->where('r.standard > ?',$min)
->where('r.standard < ?',$max)
->order('l.pointsTotal DESC');
return $this->fetchAll($sql);
}
....
Any ideas/suggestions?