Skip to content

Instantly share code, notes, and snippets.

@elinw
Created December 7, 2011 14:48
Show Gist options
  • Save elinw/1443077 to your computer and use it in GitHub Desktop.
Save elinw/1443077 to your computer and use it in GitHub Desktop.
Case When Example
$db = $this->getDbo();
$query = $db->getQuery(true);
//sqlsrv changes
$case_when = ' CASE WHEN ';
$case_when .= $query->charLength('a.alias');
$case_when .= ' THEN ';
$a_id = $query->castAsChar('a.id');
$case_when .= $query->concatenate(array($a_id, 'a.alias'), ':');
$case_when .= ' ELSE ';
$case_when .= $a_id.' END as slug';
$case_when1 = ' CASE WHEN ';
$case_when1 .= $query->charLength('c.alias');
$case_when1 .= ' THEN ';
$c_id = $query->castAsChar('c.id');
$case_when1 .= $query->concatenate(array($c_id, 'c.alias'), ':');
$case_when1 .= ' ELSE ';
$case_when1 .= $c_id.' END as catslug';
$query->select($this->getState('item.select', 'a.*') . ','.$case_when.','.$case_when1);
$query->from('#__contact_details AS a');
// Join on category table.
$query->select('c.title AS category_title, c.alias AS category_alias, c.access AS category_access');
$query->join('LEFT', '#__categories AS c on c.id = a.catid');
// Join over the categories to get parent category titles
$query->select('parent.title as parent_title, parent.id as parent_id, parent.path as parent_route, parent.alias as parent_alias');
$query->join('LEFT', '#__categories as parent ON parent.id = c.parent_id');
$query->where('a.id = ' . (int) $pk);
// Filter by start and end dates.
$nullDate = $db->Quote($db->getNullDate());
$nowDate = $db->Quote(JFactory::getDate()->format('Y-m-d H:i:s'));
// Filter by published state.
$published = $this->getState('filter.published');
$archived = $this->getState('filter.archived');
if (is_numeric($published)) {
$query->where('(a.published = ' . (int) $published . ' OR a.published =' . (int) $archived . ')');
$query->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')');
$query->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')');
}
$db->setQuery($query);
$data = $db->loadObject();
if ($error = $db->getErrorMsg()) {
throw new JException($error);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment