Skip to content

Instantly share code, notes, and snippets.

@jaybill
Created March 3, 2012 02:19
Show Gist options
  • Save jaybill/1963788 to your computer and use it in GitHub Desktop.
Save jaybill/1963788 to your computer and use it in GitHub Desktop.
getWhereClauseForKeywords
function getWhereClauseForKeywordsTwo($keywords)
{
$keywords = explode(" ", $keywords);
$select = $this->select();
foreach ($keywords as $word)
{
$subselect = $this->select();
foreach ($this->_keyword_search_field_names as $field)
{
$subselect->orWhere($field.' like ?',"%" . $word . "%");
}
$select->where( implode(" ",$subselect->getPart("where")) );
}
$where = implode(" ",$select->getPart("where"));
return $where;
}
_keyword_search_field_names = array("title","description");
getWhereClauseForKeywords("bob steve hammer"):
"1 = 1 and (0 = 1 or title like '%bob%' or description like '%bob%') and (0 = 1 or title like '%steve%' or description like '%steve%') and (0 = 1 or title like '%hammer%' or description like '%hammer%')"
getWhereClauseForKeywordsTwo("bob steve hammer"):
"((title like '%bob%') OR (description like '%bob%')) AND ((title like '%steve%') OR (description like '%steve%')) AND ((title like '%hammer%') OR (description like '%hammer%'))"
@jaybill
Copy link
Author

jaybill commented Mar 3, 2012

So what I did here was to make use of two ZF select objects, then grab only the "where" bits. "where" is an array, so you implode it with spaces and you get a string. The select logic handles all the business with including "AND" and "OR" for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment